[英]Why does my shell script display different output if each command is run individually?
I have the following shell script 我有以下shell脚本
#!/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 当我将它作为
./test.sh
或sh test.sh
运行时,它会输出
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? 为什么我看到这个额外的输出?如何在运行shell脚本时抑制这个额外的输出?
Before testing, make sure your current shell is /bin/sh
, not /bin/bash
. 在测试之前,确保您当前的shell是
/bin/sh
,而不是/bin/bash
。
As far as I known: &>
is a new feature in bash
, not in the old sh
. 据我知道:
&>
是一个新功能bash
,而不是在旧sh
。
Instead of using &>/dev/null
do it as >/dev/null 2>&1
. 而不是使用
&>/dev/null
将其作为>/dev/null 2>&1
。 This would make your script work even with ancient sh
shells. 这将使您的脚本即使使用古老的
sh
shell也可以工作。 You can also change your header to #!/bin/bash
if you indeed have bash. 如果确实有bash,你也可以将标题更改为
#!/bin/bash
bash。 Or see output of which bash
to know. 或者看看要知道
which bash
输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.