What does this little code snippet do? I do understand the test command. My question is: What does >&2
mean?
if test ! -d "$1" ; then
echo "Directory does not exist" >&2 ; exit 6
fi
Thanks in advance!
What does this little code snippet do? I do understand the test command. My question is: What does >&2
mean?
if test ! -d "$1" ; then
echo "Directory does not exist" >&2 ; exit 6
fi
Thanks in advance!
It redirects the stdout
to stderr
.
When you do:
echo "Directory does not exist"
The message goes to standard output(1) . >&2
redirects it to standard error (2). This is useful when you want to capture stdout and stderr separately.
For example, if this is in a script my_scr.sh
then running it as:
bash my_scr.sh > out_file 2> err_file
will ensure all errors are captured in err_file
and other output goes into out_file
.
Output is of two type which are STDOUT
and STDERR
.
STDOUT
is default and also denotes with '1'.
STDERR
is denoted with '2'.
So whenever you execute any command and if you want to redirect only output gets redirected not the error.
ls > out (or) ls 1>out
So the output of ls
command is not redirected to a file out.
Now we will try to print a error.
lss > out
-bash: lss: command not found
Here you got the output which is a error and cannot be redirected hence to redirect errors we use 2 while redirecting.
lss 2>out
So the same way not in your script if you display some message it is output and if you want to make it displayed as error you need to redirect output to error.
#!/bin/bash
echo "Directory not exist"
./script.sh >out
#!/bin/bash
echo "Directory not exist" >&2
./script.sh >out
Directory not exist
In the second case even though you are redirecting the message got printed on the screen as error.
Hope this helps!