Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Please see the following shell transcript:

$ ls
input.txt  test-amp-gt.sh  test-both-2.sh  test-both.sh  test-gt.sh

$ cat input.txt
input file

$ cat test-gt.sh
#! /bin/sh
cat input.txt > /dev/null && echo "DEBUG >"

$ ./test-gt.sh
DEBUG >

$ cat test-amp-gt.sh
#! /bin/sh
cat input.txt &> /dev/null && echo "DEBUG &>"

$ ./test-amp-gt.sh
DEBUG &>
$ input file
^C
$


$ cat test-both.sh
#! /bin/sh
cat input.txt > /dev/null && echo "DEBUG >"
echo "***"
cat input.txt &> /dev/null && echo "DEBUG &>"

$ ./test-both.sh
DEBUG >
***
DEBUG &>
$ input file
^C
$

$ cat test-both-2.sh
#! /bin/sh
cat input.txt &> /dev/null && echo "DEBUG &>"
echo "***"
cat input.txt > /dev/null && echo "DEBUG >"

$ ./test-both-2.sh
DEBUG &>
***
input file
DEBUG >
$

It was not clear to me as to why the redirect &> to /dev/null is apparently not working properly when the plain > is working fine. That is, in running test-amp-gt.sh, the contents of the text file should not have been output but they are. test-both-2.sh shows an even more curious behaviour of the &> -- the text should not have been output at all, but not only is it being output, but it is output after the output of the echo command on the next line!

Why is this?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Because you aren't using bash, or another shell that understands &>. Notice the line at the top of your shell scripts:

#!/bin/sh

These shell scripts will run with /bin/sh. On many systems that is symlinked to bash, but apparently not on yours. Most likely, it is dash, or some other lightweight alternative.

& is used to put commands in the background in shell scripts. Your shell is interpreting the & in &> with this meaning. So in test-amp-gt.sh:

#! /bin/sh
cat input.txt &> /dev/null && echo "DEBUG &>"

It first starts cat input.txt in the background, then sees > /dev/null which it apparently ignores, and then runs echo DEBUG &>, which outputs as it should. Your script then completes, the shell you invoked test-amp-gt.sh from prints its prompt, and then the cat in the background outputs input.txt.

share|improve this answer
1  
Thanks wingedsubmariner -- I later figured this out myself but unix.SE wouldn't let me answer my own question within 8 hours as I'm new to the site. Thanks for your kind help anyhow! –  jamadagni Dec 8 '13 at 6:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.