21.07.2015 Views

Linux Journal | December 2012 | Issue 224 - ACM Digital Library

Linux Journal | December 2012 | Issue 224 - ACM Digital Library

Linux Journal | December 2012 | Issue 224 - ACM Digital Library

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

COLUMNSWORK THE SHELLNow, what about identifying if the output is aninteractive terminal, file or pipe?stdin coming from a pipe or file$ cat inter.sh | sh inter.shstdin coming from a pipe or filePerfect. Now, what aboutidentifying if the output is aninteractive terminal, file or pipe?It turns out that you can use thesame basic test, just replace thefile ID 0 with #1:if [ -t 1 ] ; thenecho output going to the screenelsefiecho output redirected to a file or pipeThe results:$ sh inter.shscript running interactivelyoutput going to the screen$ sh inter.sh | catscript running interactivelyoutput redirected to a file or pipe$ sh inter.sh > output.txt$ cat output.txtscript running interactivelyoutput redirected to a file or pipePretty cool, actually.Let’s back up a bit and have anotherlook at file redirection before leavingthis topic, however.I already talked about the commontrick of 2>&1 to redirect stderrto stdout—something that’s veryhelpful on the command line. Youalso can redirect specific lines ofoutput in a shell script to stderr, soyour error messages are sent to thescreen even if stdout is being sent toa pipe or file:echo Error: this is an error message >&2But, what if you want to haveyour script force stdout to a specifictarget regardless of what someonedoes on the command line? It canbe done—of course—although itinvolves a very different approach:the use of the exec command.At its most basic, the exec call islike a subshell invocation (which isreally what happens each time youinvoke any system command like lsor fmt), but it’s the existing shellthat’s replaced with the specifiedcommand, effectively killing thecurrent process. If you have a shellscript that sets up specific parametersWWW.LINUXJOURNAL.COM / DECEMBER <strong>2012</strong> / 39

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!