Explore BrainMass

Shell scripting: few questions related to I/O redirection

1. Will the following only print the text "I FOUND A MATCH" to standard output when the grep is successful?

if grep "mrichard" /etc/passwd; then echo "I FOUND A MATCH"; fi

2. Does the following command send both standard output and standard error to the same file for the command cmd1?

cmd1 2>&1 >outfile

3. Does cmd2 receive both the standard error and standard output of cmd1 as standard input?

cmd1 2>&1 | cmd2

4. Will the script below always print out the text 'They are the same' assuming the script ran under the Bourne shell?


if [ ! -s "$infile" ]
exit 1

linecnt=`wc -l $infile | while read cnt rest
echo $cnt

while read line
mycnt=`expr $mycnt + 1`
done < $infile

if [ $linecnt -eq $mycnt ]
echo They are the same
echo They are different.

5. Does the standard output of this script get sent to STDOUT?


exec 4>&1
exec 1>&2
exec 2>&4
exec 4>&-
echo Hello
echo More text

6. Is the visible output of this script, the text 'Hello'?


exec 4>&2
exec 2>&1
exec 1>&4
exec 4>&-
echo Hello
) 2> /dev/null

Solution Preview

1. No. It will also print all the lines containing mrichard.

2. No. It sends only standard output to outfile, because the standard error was duplicated as standard output (i.e. file descriptor 2 was made to be a copy of file descriptor 1) before standard output redirection.

3. Yes. ...

Solution Summary

Solution gives sufficient explanation for the answers to I/O redirection questions.