The following command lets me check if a webpage has specific content. It does not output anything unless the content is found.
curl -v --silent https://somedomain.com/somepage.html 2>&1 | grep 'some content'
The problem is, when I add this to a shell script, the output isn't suppressed any more.
#!/bin/bash
TEST1="curl -v --silent https://somedomain.com/somepage.html 2>&1 | grep 'some content'"
$TEST1
if [[ $? != 0 ]]; then
#do something if exit status of last command not equal to zero
fi
I have the same problem if I try to store the output of the script in a variable (VAL1
)
#!/bin/bash
TEST1="curl -v --silent https://somedomain.com/somepage.html 2>&1 | grep 'some content'"
VAL1+=$($TEST1)
echo "result should be blank or the found grep $VAL1"
Why does 2>&1
work as expected when running the command directly, but when added to a script the output is directed in the command line?
Update
Jeffs hint's in the comments got me going in the right direction. The accepted answer is correct. The work around I did for my script was to move the code I originally tried to assign to a variable to be in a function and use $( ... )
. This way everything ran as expected:
#!/bin/bash
# note that -z checks if variable is empty
test1() {
VAL1=$(curl -v --silent https://somedomain.com/somepage.html 2>&1 | grep 'some content')
if [[ -z $VAL1 ]]; then
VAL1=test1fail
fi
}
test1
echo $VAL1
set -x
:curl ... '2>&1' ...
with the single-quotes around the redirection.