简体   繁体   中英

Why does my shell script display different output if each command is run individually?

I have the following shell script

#!/bin/sh
keyExists=`stat ~/.ssh/id_rsa &> /dev/null; echo $?`
echo $keyExists

When I run it as ./test.sh or sh test.sh it outputs

0 File: `/home/vagrant/.ssh/id_rsa' Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: fc00h/64512d Inode: 2888560 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 1000/ vagrant) Gid: ( 1000/ vagrant) Access: 2014-07-23 11:40:33.355848310 -0400 Modify: 2014-07-23 11:40:33.355848310 -0400 Change: 2014-07-23 11:40:33.355848310 -0400 Birth: -

However when I run each command individually on the command line

keyExists=`stat ~/.ssh/id_rsa &> /dev/null; echo $?`
echo $keyExists

I get the output

0

Why am I seeing this additional output and how do I suppress this additional output when I run the shell script?

Before testing, make sure your current shell is /bin/sh , not /bin/bash .

As far as I known: &> is a new feature in bash , not in the old sh .

Instead of using &>/dev/null do it as >/dev/null 2>&1 . This would make your script work even with ancient sh shells. You can also change your header to #!/bin/bash if you indeed have bash. Or see output of which bash to know.

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