为什么我的带有反引号的 if 语句不能正常工作? [英] Why doesn't my if statement with backticks work properly?

查看:36
本文介绍了为什么我的带有反引号的 if 语句不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个 Bash 脚本,用户可以在其中复制文件,并查看它是否成功完成.但是每次复制完成时,无论正确与否,都会显示第二个输出未完成复制".知道如何解决这个问题吗?

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

推荐答案

你想要的是

if cp -i "$file" "$destination"; then #...

不要忘记引号.

你的版本:

if [ `cp -i $files $destination` ];then #..

将始终执行 else 分支.

shell 中的if 语句接受一个命令.如果该命令成功(返回 0,分配到 $?),则条件成功.

The if statement in the shell takes a command. If that command succeeds (returns 0, which gets assigned into $?), then the condition succeeds.

如果你这样做 if [ ... ];然后,那么就和如果测试...;然后 因为[ ]test<的语法糖/a> 命令/内置.

If you do if [ ... ]; then, then it's the same as if test ... ; then because [ ] is syntactic sugar for the test command/builtin.

在您的情况下,您将 cp 操作的 stdout* 的结果作为参数传递给 test

In your case, you're passing the result of the stdout* of the cp operation as an argument to test

cp 操作的 stdout 将为空(cp 一般只输出错误,然后到 stderr>).带有空参数列表的 test 调用是一个错误.该错误导致非零退出状态,因此您始终会获得 else 分支.

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.

*$() 进程替换或反引号进程替换 slurp stdout 他们运行的命令

*the $() process substitution or the backtick process substitution slurp the stdout of the command they run

这篇关于为什么我的带有反引号的 if 语句不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆