0

Here is my command in the shell script. I want all the output to be redirected to a standard Log File. It does that fine except at when it does not find the *.txt files with a directory or sub directory, it writes the o/p to std output screen. How to suppress this and send it to the Log file.

TOTALFILES=`ls $SOURCEDIR/$SOURCESUBDIR/*.txt| wc -l` >> $WORKDIR/$LOGFNAME
jesse_b
  • 37,005
veekay
  • 1

1 Answers1

0

It does not "write the o/p to std output". It writes it to stderr. Also it won't write stdout to your file either. When you use command substitution you are telling it to write stdout to the variable TOTALFILES.

If you want your output to go to both the variable and the file you will need to use tee:

totalfiles=$(ls "${sourcedir}/${sourcesubdir}/"*.txt | wc -l | tee "${workdir}/${logfname}")

However this also wont send stderr to your log file, to do that you could do:

totalfiles=$(ls "${sourcedir}/${sourcesubdir}/"*.txt 2>"${workdir}/${logfname}" | wc -l | tee "${workdir}/${logfname}")

stdin is fd0
stdout is fd1
stderr is fd2

To redirect stdout:

foo > /path/file

Which is equivalent to:

foo 1> /path/file

To redirect stderr:

foo 2> /path/file

To redirect both:

foo > /path/file 2>&1

Note that the order of redirections is significant

Reading: 3.6 Redirections


With bash you can also shorten this using &> for example:

foo &> /path/file

(You should avoid uppercase variable names, you should also quote all your variables and use $( ... ) instead of backticks.

jesse_b
  • 37,005
  • TOTALFILES=ls $SOURCEDIR/$SOURCESUBDIR/*.txt| wc -l >> $WORKDIR/$LOGFNAME 2>&1 . THis is not working for me.. – veekay Jul 11 '19 at 19:06
  • @veekay: Yes it should not work, you have not read my answer. – jesse_b Jul 11 '19 at 19:14
  • 1
    Also, it's generally better to use set with the globbing pattern and then $# to see how many names matched (with nullglob set in bash). – Kusalananda Jul 11 '19 at 19:17
  • @Jesse_b I missed checking the initial response and it works fine.. what is the significance of NOT using uppercase variable names.. – veekay Jul 11 '19 at 20:36