简体   繁体   中英

Pipe with `tee` in a `for` loop

This is probably a newbie's escaping problem. I'm trying run command in a for loop like this

$ for SET in `ls ../../mybook/WS/wsc_production/`; do ~/sandbox/scripts/ftype-switch/typesort.pl /media/mybook/WS/wsc_production/$SET ./wsc_sorter/$SET | tee -a sorter.log; done;

but I end up with sorter.log being empty. (I'm sure there is some output.) If I escape the pipe symbol ( \\| ), I end up with no sorter.log at all.

What am I doing wrong?

$ bash --version
GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)

Edit: Oops, /media/mybook/ fell asleep, so there actually was no output . The code was correct in the first place. Thanks to all for comments, though.

You're using tee , so if there is output, you'd see it on your terminal. What do you see?

If you see output, it's probably stderr you're seeing, so you might want to redirect it:

dir1=$HOME/sandbox/scripts/ftype-switch
dir2=/media/mybook/WS/wsc_production
for SET in ../../mybook/WS/wsc_production/*; do 
  $dir1/typesort.pl $dir2/$SET ./wsc_sorter/$SET 2>&1 | tee -a sorter.log
done

Glenn said it well. I would like to offer a different angle: you can move the 'tee' command outside of the for loop. The advantage to this approach is tee is invoked only once:

dir1=$HOME/sandbox/scripts/ftype-switch
dir2=/media/mybook/WS/wsc_production
for SET in ../../mybook/WS/wsc_production/*; do 
  $dir1/typesort.pl $dir2/$SET ./wsc_sorter/$SET 2>&1 
done | tee -a sorter.log

My deepest apologies, the problem was somewhere else and my script actually did not output anything at all. Now it works.

Two reasons why I got the illusion that the problem is in escaping:

  • of course, lack of confidence in bash scripting, which is effect of lack of knowledge and experience
  • and also, lack of attention--it did not come into my mind that the disk on USB fell asleep, so when I tried the loop there actually was no output

Well, that's for some stumbling on my way to knowledge... :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM