在shell中运行多行命令
说我有一个文件/templates/apple ,我想
- 把它放在两个不同的地方,然后
- 删除原来的。
所以, /templates/apple将被复制到/templates/used AND /templates/inuse ,然后之后,我想删除原来的。
是cp最好的办法做到这一点,其次是rm ? 或者,还有更好的方法?
我想在一行中完成,所以我认为它看起来像这样:
cp /templates/apple /templates/used | cp /templates/apple /templates/inuse | rm /templates/apple
这是正确的语法?
您正在使用| (pipe道)将命令的输出引导到另一个命令。 你正在寻找的是&&操作符只有在前一个成功执行下一个命令:
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
要么
cp /templates/apple /templates/used && mv /templates/apple /templates/inuse
总结(非详尽地)bash的命令操作符/分隔符:
-
|将一个命令的标准输出(stdout)pipe道(pipe道)转换为另一个命令的标准input。 请注意,stderr仍会进入其默认目的地,无论发生什么情况。 -
|&将一个命令的stdout和stderr同时input到另一个命令的标准input中。 非常有用,在bash版本4及以上版本中可用。 -
&&只有在前一个成功的情况下才执行&&的右侧命令。 -
||执行||的右侧命令 只有前一个失败了。 -
;执行右边的命令 总是不pipe前面的命令是成功还是失败。 除非set -e之前被调用,这会导致bash在发生错误时失败。
为什么不cp到位置1,然后mv到位置2.这需要“删除”原来的照顾。
不,这不是正确的语法。 | 用于从一个程序“输出”输出,并将其转化为下一个程序的input。 你想要的是什么; ,分离多个命令。
cp file1 file2 ; cp file1 file3 ; rm file1
如果你需要单个命令必须在下一个可以开始之前完成,那么你可以使用&&代替:
cp file1 file2 && cp file1 file3 && rm file1
这样,如果任一个cp命令失败, rm将不会运行。
请注意cp AB; rm A cp AB; rm A正好是mv AB 。 它也会更快,因为您不必真正复制字节(假设目标位于同一个文件系统上),只需重命名该文件即可。 所以你想要cp AB; mv AC cp AB; mv AC
尝试这个..
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
另一个选项是在每个命令的末尾键入Ctrl + V Ctrl + J。
示例(使用Ctrl + V Ctrl + Jreplace# ):
$ echo 1# echo 2# echo 3
输出:
1 2 3
这将执行命令,无论以前的失败。
相同: echo 1; echo 2; echo 3 echo 1; echo 2; echo 3
如果你想在失败的命令上停止执行,在除最后一行之外的每一行的末尾添加&& 。
示例(使用Ctrl + V Ctrl + Jreplace# ):
$ echo 1 &&# failed-command &&# echo 2
输出:
1 failed-command: command not found
在zsh您也可以使用Alt + Enter或Esc + Enter代替Ctrl + V Ctrl + J
使用pipe道似乎对我来说很奇怪。 无论如何,你应该使用逻辑和bash运算符。
$ cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apples
如果cp命令失败,rm将不会被执行。
或者,您可以使用for循环和cmp来制作更详细的命令行。
雷诺
非常简单:只需在每个命令之间使用&&
逻辑是cp file1 file2 && cp file1 file3 && rm file1
EG 1:
cp /templates/apple /templates/used && mv /templates/apple /templates/inuse
EG 2:
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
编辑:它为我工作。