How to capture actual error message when a command fails to execute

I want to capture actual error message in case the commands I use in my shell script fails.

For eg:
ls -l abc.txt 2>>errorlog.txt

In this case I understand the error message is written to the errorlog.txt and I assume its bacause the return code from the command ls -l abc might return 2 if "abc" doesnt exists.

My question is: How about if the command return non zero return code and is not equal to 2?

I want to do something like this:

ls -l abc.txt
if [$? -ne 0]
then
echo $errorMessage >> errorlog.txt
fi

where I want actual error message that the command has returned to be written to errorlog.txt. Just for understanding I used $errorMessage but I assume there should be some means to capture the actual error message which can later be stored in errorMessage or written directly to errorlog.txt.
Can someone please help?

cheers,
Devaraj Takhellambam

Okay, let's see:

That's correct.

Nope, your assumption is incorrect.
The number 2 is not some return code that you are capturing in errlog.txt. Instead, it is the file descriptor of the stderr file. The three files - stdin, stdout and stderr are always open and have the descriptors 0, 1 and 2 assigned to them respectively. By default, stdin is your keyboard, stdout is your screen and stderr is your screen as well. Which means, by default, all error messages are directed to your screen. If you want to redirect an error message to something other than the screen (a file, for instance), then you'd use the construct "2>err.txt" after the command, which redirects the error message to the file "err.txt".

If the command returns a return code other than 2, it will still be captured in "err.txt" if you put the construct "2>err.txt" after that command.
An example follows:

$
$ # The telnet command returns an error code 1 if the target host is unknown
$ # The error code is stored in the "$?" variable that is echo'd right after the command.
$
$ telnet xxx
telnet: xxx: Name or service not known
xxx: Unknown host
$
$ echo $?
1
$

So now if I put "2>err.txt", then this error message should be redirected to "err.txt". As you can see, the error code here is something other than 2.

$ # try the command again and redirect the stderr to a file
$ 
$ telnet xxx 2>err.txt
$
$ # Check the file "err.txt"
$
$ cat err.txt
telnet: xxx: Name or service not known
xxx: Unknown host
$
$ # The error message was redirected to the file, and the error code was *not equal to* 2
$
$

Hope that helps,
tyler_durden

It sounds like you just want to capture the value of '$?':

ls -l abc.txt >/dev/null
rc=$?
if [[ $rc -ne 0 ]]; then
  echo "Error was: $rc" >> errorlog.txt
fi