在 shell 中的一行中运行多个命令 [英] Running multiple commands in one line in shell

查看:58
本文介绍了在 shell 中的一行中运行多个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文件 /templates/apple 并且我想要

Say I have a file /templates/apple and I want to

  1. 把它放在两个不同的地方,然后
  2. 删除原来的.

因此,/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 仍会进入其默认目标.
  • |& 将一个命令的 stdoutstderr 通过管道传输到另一个命令的标准输入中.非常有用,可在 bash 版本 4 及更高版本中使用.
  • && 仅在前一个成功时才执行 && 的右侧命令.
  • || 执行 || 右侧的命令,只是前一个命令失败.
  • ; 总是执行 ; 右边的命令,不管上一个命令是成功还是失败.除非之前调用了 set -e,否则会导致 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.

这篇关于在 shell 中的一行中运行多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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