为什么我若与反引号语句正常工作? [英] Why doesn't my if statement with backticks work properly?
问题描述
我试图做一个Bash脚本,用户将能够复制一个文件,看它是否已成功完成与否。但每一次复制完成后,正常与否,第二输出复制却没有这样做字样。任何想法如何解决这个问题?
如果[`CP -i $文件$ destination`;然后
回声复制成功。
其他
回声复制却没有这样做
科幻
您需要的是
如果CP -i$文件,$目的地;然后 #...
<一个href=\"http://unix.stackexchange.com/questions/16303/what-is-the-significance-of-single-and-double-quotes-in-environment-variables\">Don't忘记引号。
您的版本:
如果[`CP -i $文件$ destination`];然后#..
将始终执行其他
分支。
的如果在Shell语句需要的命令。
如果这个命令执行成功,则条件成功(这被分配到 $?
收益 0
)。
如果您如果[...]然后
,那么它的同如果测试...;然后
,因为 []
是语法糖的的测试命令/内置的。
在你的情况,你传递在标准输出* 的结果 CP的
操作作为参数传递给测试
在标准输出 CP
的操作将是空的( CP
一般只输出错误和那些转至标准错误)。 A 测试
调用一个空的参数列表是一个错误。在一个非零退出状态错误的结果,从而始终获得其他
分支。
*的 $()
进程替换或反引号进程替换思乐普在标准输出它们运行的命令
I am trying to make a Bash script where the user will be able to copy a file, and see if it was successfully done or not. But every time the copy is done, properly or not, the second output "copy was not done" is shown. Any idea how to solve this?
if [ `cp -i $files $destination` ];then
echo "Copy successful."
else
echo "Copy was not done"
fi
What you want is
if cp -i "$file" "$destination"; then #...
You version:
if [ `cp -i $files $destination` ];then #..
will always execute the else
branch.
The if statement in the shell takes a command.
If that command succeeds (returns 0
, which gets assigned into $?
), then the condition succeeds.
If you do if [ ... ]; then
, then it's the same as
if test ... ; then
because [ ]
is syntactic sugar for the test command/builtin.
In your case, you're passing the result of the stdout* of the cp
operation as an argument to test
The stdout of a cp
operation will be empty (cp
generally only outputs errors and those go to stderr). A test
invocation with an empty argument list is an error. The error results in a nonzero exit status and thus you always get the else
branch.
*the $()
process substitution or the backtick process substitution slurp the stdout of the command they run
这篇关于为什么我若与反引号语句正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!