0

i have the below shell script:

pankaj@pankaj-Lenovo-G500:~$ cat demoscr
if [ $# -ne 2 ]
then
   echo "Error : Number are not supplied" 1>&2
   echo "Usage : $0 number1 number2" 1>&2
   exit 1
fi
ans=`expr $1 + $2`
echo "Sum is $ans"

when i run the shell script, error message is being printed but nothing is present in the er1 file. why?

pankaj@pankaj-Lenovo-G500:~$ ./demoscr > er1
Error : Number are not supplied
Usage : ./demoscr number1 number2
pankaj@pankaj-Lenovo-G500:~$ cat er1
pankaj@pankaj-Lenovo-G500:~$ cat er1

1 Answers1

2

The simple > operator redirects STDOUT to a file. However, your script is printing to STDERR (see the 1>&2 at the end of your echo commands). That's why you see the text in the terminal and not in the log file.

You need to redirect the output of the script using 2> (redirect STDERR only) or &> (redirect both STDOUT and STDERR) instead.

See How do I save terminal output to a file? for more details about output redirection to files in Bash.

Byte Commander
  • 107,489