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

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

问题描述

说我有一个文件/templates/apple,我想

  1. 将其放在两个不同的地方,然后
  2. 删除原件.

因此,/templates/apple将被复制到/templates/used/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天全站免登陆