在 shell 中的一行中运行多个命令 [英] Running multiple commands in one line in shell
问题描述
假设我有一个文件 /templates/apple
并且我想要
Say I have a file /templates/apple
and I want to
- 把它放在两个不同的地方,然后
- 删除原来的.
因此,/templates/apple
将被复制到 /templates/used
AND /templates/inuse
然后我想删除原来的.
So, /templates/apple
will be copied to /templates/used
AND /templates/inuse
and then after that I’d like to remove the original.
cp
是最好的方法,其次是 rm
吗?或者有更好的方法吗?
Is cp
the best way to do this, followed by rm
? Or is there a better way?
我想在一行中完成所有操作,所以我认为它看起来像:
I want to do it all in one line so I’m thinking it would look something like:
cp /templates/apple /templates/used | cp /templates/apple /templates/inuse | rm /templates/apple
这是正确的语法吗?
推荐答案
您正在使用 |
(管道)将命令的输出定向到另一个命令.您正在寻找的是 &&
操作符,只有在前一个命令成功时才执行下一个命令:
You are using |
(pipe) to direct the output of a command into another command. What you are looking for is &&
operator to execute the next command only if the previous one succeeded:
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
或者
cp /templates/apple /templates/used && mv /templates/apple /templates/inuse
<小时>
总结(非详尽地)bash 的命令操作符/分隔符:
To summarize (non-exhaustively) bash's command operators/separators:
|
将一个命令的标准输出 (stdout
) 通过管道(管道)导入另一个命令的标准输入.请注意,无论发生什么情况,stderr
仍会进入其默认目标.|&
将一个命令的stdout
和stderr
通过管道传输到另一个命令的标准输入中.非常有用,可在 bash 版本 4 及更高版本中使用.&&
仅在前一个成功时才执行&&
的右侧命令.||
执行||
右侧的命令,只是前一个命令失败.;
总是执行;
右边的命令,不管上一个命令是成功还是失败.除非之前调用了set -e
,否则会导致bash
在出错时失败.
|
pipes (pipelines) the standard output (stdout
) of one command into the standard input of another one. Note thatstderr
still goes into its default destination, whatever that happen to be.|&
pipes bothstdout
andstderr
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. Unlessset -e
was previously invoked, which causesbash
to fail on an error.
这篇关于在 shell 中的一行中运行多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!