I am starting with scripting in ubuntu. Its very easy and good thing to do. In my shell scripting, I need to run few linux command to change directory, or to remove files or copy files or any other command. So I was just wondering is this possible to get the command not found notification in scripting so that if any command fails at any time, we can show error message on terminal to user.

I searched a little about this on google and found out that using below we can read the terminal response:

echo "Response: $fooVar"

So above I am running ls command so on terminal it looks like something:


But if I do something like

echo "Response: $fooVar"

It gives me error lsv command not found which is ok because lsv is not a command but this string should come like this

Response: lsv command not found

Is this possible or I am going into wrong way. Also how can we put an if condition for this error. Please help. Thanks


The error,

lsv command not found

is send to stderror whereas normal output are sendt to stdout. You will have to redirect stderror to stdout:

$ fooVar=$(lsv 2>&1)
$ echo "Response: $fooVar"
Response: -bash: lsv: command not found

This is almost what you want, execpt for the -bash:

Stdout has filedescriptor 1 and stderr has descriptor 2. So what i says is 'send stderr to the same place as stdout'. You could use somthing similar to put output or errors to files:

ls > outfile 2> errorfile

Will put the normal output in a file called 'outfile', and eventual errors in 'errfile'.

ls >> outfile 2>> errorfile

Will append to the files instead of resetting them. And you can use only the one or the other redirect.

  • Thank You for telling me about stderror. I will study more on it. Can you please explain what does 2>&1 means in your first line. Also how can we put if statement for this condition – S Andrew Jan 31 '17 at 9:25

Try this:

echo -n "Response "; echo `$fooVar`
  • You almost failed to make it wrong ;-) THe variable, fooVar, doesn't contain the error message, when the command is wrong, and the output isn't displayed correctly when the command is correct. – Soren A Jan 31 '17 at 9:47
  • what does -n with echo indicates – S Andrew Jan 31 '17 at 9:49
  • 1
    -n is 'no newline' .. – Soren A Jan 31 '17 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.