我有以下shell脚本
#!/bin/sh
keyExists=`stat ~/.ssh/id_rsa &> /dev/null; echo $?`
echo $keyExists
当我以./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: -
但是,当我在命令行上单独运行每个命令时
keyExists=`stat ~/.ssh/id_rsa &> /dev/null; echo $?`
echo $keyExists
我得到了输出
0
为什么我会看到这个额外的输出?如何在运行shell脚本时抑制这个额外的输出?
答案 0 :(得分:2)
在测试之前,请确保您当前的shell为/bin/sh
,而不是/bin/bash
。
据我所知:&>
是bash
中的新功能,而不是旧版sh
。
答案 1 :(得分:1)
而不是&>/dev/null
使用>/dev/null 2>&1
。这将使您的脚本即使使用古代sh
shell也能正常工作。如果您确实有bash,也可以将标题更改为#!/bin/bash
。或者查看which bash
的输出以了解。