验证副本是否成功

Edd*_*One 10 shell conditional if-statement

我想编写一个脚本来验证副本是否成功.这就是我所拥有的:

#!/bin/sh
cp home/testing/present.txt home/testing/future.txt
   echo "Copy Code: $? - Successful"
if [ $? != 0 ]; then
   echo "Copy Code: $? - Unsuccessful"
fi
Run Code Online (Sandbox Code Playgroud)

"if"语句未初始化.怎么解决这个?感谢您的时间.

tha*_*guy 33

$? 指的是最后一个命令:

#!/bin/sh
cp home/testing/present.txt home/testing/future.txt
   echo "Copy Code: $? - Successful"   # last command: cp
if [ $? != 0 ]; then                   # last command: echo
   echo "Copy Code: $? - Unsuccessful" # last command: [
fi
Run Code Online (Sandbox Code Playgroud)

如果要重复使用特定命令的状态,只需将结果保存在另一个变量中:

#!/bin/sh
cp home/testing/present.txt home/testing/future.txt
status=$?
echo "Copy Code: $status - Successful"
if [ $status != 0 ]; then
   echo "Copy Code: $status - Unsuccessful"
fi
Run Code Online (Sandbox Code Playgroud)

但是,更好的方法是首先简单地测试cp命令:

if cp home/testing/present.txt home/testing/future.txt
then
  echo "Success"
else
  echo "Failure, exit status $?"
fi
Run Code Online (Sandbox Code Playgroud)


Jon*_*ler 9

简化,简化和简化:

#!/bin/sh
if cp home/testing/present.txt home/testing/future.txt; then
   echo "Copy Code: $? - Successful"
else
   echo "Copy Code: $? - Unsuccessful"
fi
Run Code Online (Sandbox Code Playgroud)

如果要测试命令是否成功,请使用if语句测试状态.

请记住,这$?是执行的最后一个命令的退出状态.它就像一个极不稳定的全局变量(在C或C++中).在您的代码中,您可以从命令中运行echo哪些clobbers值.如果需要显式捕获,请在需要捕获其状态的命令后立即执行此操作:$?cp$?

cp home/testing/present.txt home/testing/future.txt
cp_status=$?
Run Code Online (Sandbox Code Playgroud)

然后$cp_status在下面的代码中测试.