I have problem to hide error message from shell command as the following case.
firs_line=$(head -n 1 file) > /dev/null 2>&1
I expect that the error message will be hidden but actually it doesn't.
How to get output while head
command is executed successfully but hide error message when it fails?
Thanks in advance.
To suppress error output in bash , append 2>/dev/null to the end of your command. This redirects filehandle 2 (STDERR) to /dev/null .
> /dev/null throw away stdout. 1> /dev/null throw away stdout. 2> /dev/null throw away stderr. &> /dev/null throw away both stdout and stderr.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
To check if two strings are equal in bash scripting, use bash if statement and double equal to== operator. To check if two strings are not equal in bash scripting, use bash if statement and not equal to!= operator.
Is the error message coming from the head
program (like, file not found)?
In this case you have to redirect the output from inside parens:
firs_line=$(head -n 1 file 2>/dev/null)
Moreover, you only have to redirect standard error (and not standard output which is supposed to be catched by $()
to be stored in firs_line
firs_line="$([ -r file ] && head -n 1 file)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With