check="$(cat "$HOME/log.txt" | grep 'some_string')"
if [ -z "${check}" ] ; then
echo "string not found"
else
echo "string found"
fi
In my bash script , i am checking for a string in a file and it outputs if the string was found or not by checking if the variable is empty ot not . Pretty simple . So the thing is when this $HOME/log.txt file is absent , it outputs
cat: /home/user/log.txt: No such file or directory
string not found
Not really wrong here but i want to suppress that "No such file or directory" message , i just simply thought of using &>/dev/null
alongside cat command to suppress this but then if i do this check="$(cat "$HOME/log.txt" &>/dev/null | grep 'some_string')"
, the resulting $check
variable always becomes empty and hence it always says string not found even when its actually there
How do i can suppress the output of cat command and retain its variable value ?
Replace &>/dev/null
by 2>/dev/null
:
check="$(cat "$HOME/log.txt" 2>/dev/null | grep 'some_string')"
Here is a brief summary of how redirections work:
2>/dev/null
will only redirect standard error;1>/dev/null
or >/dev/null
will only redirect standard output.&>/dev/null
will redirect both standard output and standard error (not POSIX);