VincentHuang
VincentHuang

Reputation: 416

Hide error message in bash

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.

Upvotes: 13

Views: 27506

Answers (2)

Cyrus
Cyrus

Reputation: 88644

firs_line="$([ -r file ] && head -n 1 file)"

Upvotes: 2

pqnet
pqnet

Reputation: 6588

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

Upvotes: 25

Related Questions