13

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.

2
  • put the error redirection inside the $(). as is its trying to redirect the assignment, not the command output Commented Aug 17, 2014 at 10:00
  • What error are you expecting that you know you can ignore the error? Presumably, you are OK with firs_line having an empty value when the call to head fails. Commented Aug 17, 2014 at 14:30

2 Answers 2

25

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

+1. It makes sense to prevent errors instead of silencing them, and the error he talks about is most likely related to files missing or not readable (any other thing would be weird and probably better if printed out). But you should explain the rationale behind your code in a couple lines for future reference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.