如果在Bash中工作,我怎么能这样做?

时间:2010-03-24 11:14:15

标签: linux bash shell

在bash中,我怎样才能使这样的结构起作用:

if (cp /folder/path /to/path) && (cp /anotherfolder/path /to/anotherpath)
then
  echo "Succeeded"
else
  echo "Failed"
fi

if应该测试$?返回每个命令的代码并将它们与&&。

联系起来

我怎样才能在Bash中做到这一点?

3 个答案:

答案 0 :(得分:13)

if cp /folder/path /to/path /tmp && cp /anotherfolder/path /to/anotherpath ;then
  echo "ok"
else
  echo "not"
fi

答案 1 :(得分:8)

cp /folder/path /to/path && cp /anotherfolder/path /to/anotherpath
if [ $? -eq 0 ] ; then
    echo "Succeeded"
else
    echo "Failed"
fi

答案 2 :(得分:2)

另一种方式:

cp /folder/path /to/path && cp /anotherfolder/path /to/anotherpath && {
  echo "suceeded"
} || {
  echo "failed"
}

我测试了它:

david@pcdavid:~$ cp test.tex a && cp test.aux b && { echo "haha"; } || { echo "hoho"; }
haha
david@pcdavid:~$ cp test.ztex a && cp test.aux b && { echo "haha"; } || { echo "hoho"; }
cp: cannot stat `test.ztex': No such file or directory
hoho
david@pcdavid:~$ cp test.tex a && cp test.zaux b && { echo "haha"; } || { echo "hoho"; }
cp: cannot stat `test.zaux': No such file or directory
hoho