假设我有一个文件/模板/苹果,我想
放在两个不同的地方,然后
去掉原来的。
因此,/templates/apple将被复制到/templates/used和/templates/inuse
然后我要把原来的去掉。
cp和rm是最好的方法吗?还是有更好的办法?
我想在一行中完成这一切,所以我认为它看起来会像这样:
cp /templates/apple /templates/used | cp /templates/apple /templates/inuse | rm /templates/apple
这样的语法正确吗?
为什么不是cp到位置1,然后mv到位置2。这是为了“移除”原始文件。
不,这不是正确的语法。|用于“管道”一个程序的输出,并将其转换为下一个程序的输入。您需要的是;,它分隔了多个命令。
cp file1 file2 ; cp file1 file3 ; rm file1
如果你要求单独的命令必须成功才能启动下一个命令,那么你可以使用&&来代替:
cp file1 file2 && cp file1 file3 && rm file1
这样,如果cp命令中的任何一个失败,rm将不会运行。
另一种选择是在每个命令的末尾输入Ctrl+V Ctrl+J。
示例(用Ctrl+V Ctrl+J替换#)
$ echo 1#
echo 2#
echo 3
输出:
1
2
3
这将执行命令,不管之前的命令是否失败。
同:echo 1;回声2;回声3
如果你想停止执行失败的命令,除了最后一行,在每一行的末尾加上&&。
示例(用Ctrl+V Ctrl+J替换#)
$ echo 1 &&#
failed-command &&#
echo 2
输出:
1
failed-command: command not found
在zsh中,你也可以使用Alt+Enter或Esc+Enter来代替Ctrl+V Ctrl+J
您正在使用|(管道)将一个命令的输出定向到另一个命令。你要找的是&&操作符,它只在前一个命令成功的情况下执行下一个命令:
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
Or
cp /templates/apple /templates/used && mv /templates/apple /templates/inuse
(非详尽地)总结bash的命令操作符/分隔符:
| pipes (pipelines) the standard output (stdout) of one command into the standard input of another one. Note that stderr still goes into its default destination, whatever that happen to be.
|&pipes both stdout and stderr of one command into the standard input of another one. Very useful, available in bash version 4 and above.
&& executes the right-hand command of && only if the previous one succeeded.
|| executes the right-hand command of || only it the previous one failed.
; executes the right-hand command of ; always regardless whether the previous command succeeded or failed. Unless set -e was previously invoked, which causes bash to fail on an error.