如何根据上一个命令的结果运行不同的命令?
例如,我尝试使用 cURL 上传 4 个文件(A、B、C、D),但有时会失败。我的脚本是这样的:
for f in `ls`
do
curl -T $f ftp.server.com
done
A、B、C 上传成功,而 D 出现某种错误。我想要做的是删除 A、B、C,只保留目录中的 D。
For example, there are 4 files (A,B,C,D) which I was try to upload with cURL, but sometimes it failed. My script is like this:
for f in `ls`
do
curl -T $f ftp.server.com
done
A,B,C were uploaded successfully, while D left with some kind of errors. What I want to do is to remove A,B,C and keep only D in the directory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您已经在小脚本中编写了一个错误:
这应该是这样的:
不同之处在于
ls
方法无法正确处理名称中带有空格的文件:现在,进入上传 - and-remove 问题:
&&
是一个短路运算符;仅当第一个命令返回退出值0
时,它才会执行第二个命令(这通常意味着进程返回值“成功”——是的,有点倒退)。有一天您可能还会发现||
运算符很有用,可以在出现故障时执行程序。也许最令人惊讶的是,您可以在一个命令上同时使用它们来根据成功或失败情况酌情执行某些操作:First things first, you've coded a bug into your little script:
This should read:
The difference is that
ls
approach won't properly handle files with whitespace in their names:Now, onto the upload-and-remove issue:
The
&&
is a short-circuit operator; it will execute the second command only if the first command returns an exit value of0
(which normally means "successful" in process return values -- yes, a little backwards). You might also someday find the||
operator useful, to execute programs if something has failed. And perhaps most surprising, you can use them both on one command to do something on success or failure as appropriate:$?
指返回码< /a>.假设“0”表示curl
上传成功,那么您需要如下所示的内容:$?
refers to the return code. Assuming "0" indicates a successfulcurl
upload, then you want something like this: