Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide error message in bash

Tags:

bash

shell

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.

like image 251
VincentHuang Avatar asked Aug 17 '14 09:08

VincentHuang


People also ask

How do I hide error messages in bash?

To suppress error output in bash , append 2>/dev/null to the end of your command. This redirects filehandle 2 (STDERR) to /dev/null .

How do I hide errors in Linux?

> /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.

What is $@ in bash?

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.

Can I use != In bash?

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.


2 Answers

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

like image 147
pqnet Avatar answered Oct 06 '22 10:10

pqnet


firs_line="$([ -r file ] && head -n 1 file)"
like image 22
Cyrus Avatar answered Oct 06 '22 08:10

Cyrus