Linux 我可以在 UNIX shell 中执行嵌套或链式命令吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3746079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:13:02  来源:igfitidea点击:

Can I execute nested or chained commands in UNIX shell?

linuxcommand-lineubuntunestedsolaris

提问by Osama Ahmad

Can I execute command within another command in UNIX shells?

我可以在 UNIX shell 中的另一个命令中执行命令吗?

If impossible, can I use the output of the previous command as the input of next command, as in:

如果不可能,我可以使用上一个命令的输出作为下一个命令的输入,例如:

command xthen command y,

command x那么command y

where in command yI want use the output of command x?

command y我想在哪里使用command x?

采纳答案by Jim Nutt

What exactly are you trying to do? It's not clear from the commands you are executing. Perhaps if you describe what you're looking for we can point you in the right direction. If you want to execute a command over a range of file (or directory) names returned by the "find" command, Colin is correct, you need to look at the "-exec" option of "find". If you're looking to execute a command over a bunch of arguments listed in a file or coming from stdin, you need to check out the "xargs" commands. If you want to put the output of a single command on to the command line of another command, then using "$(command)" (or 'command' [replace the ' with a backquote]) will do the job. There's a lot of ways to do this, but without knowing what it is you're trying it's hard to be more helpful.

你到底想做什么?从您正在执行的命令中不清楚。也许如果您描述了您正在寻找的内容,我们可以为您指明正确的方向。如果要对“find”命令返回的一系列文件(或目录)名称执行命令,Colin 是正确的,则需要查看“find”的“-exec”选项。如果您希望对文件中列出的或来自标准输入的一堆参数执行命令,则需要查看“xargs”命令。如果您想将单个命令的输出放到另一个命令的命令行上,那么使用“$(command)”(或“command”[用反引号替换 '])就可以完成这项工作。有很多方法可以做到这一点,但在不知道它是什么的情况下,你正在尝试它”

回答by Colin Hebert

You can use the backquotes for this.

您可以为此使用反引号。

For example this will cat the file.txt

例如,这将 cat file.txt

cat `echo file.txt`

cat `echo file.txt`

And this will print the date

这将打印日期

echo the date is `date`

echo 日期是`date`

The code between back-quotes will be executed and be replaced by its result.

反引号之间的代码将被执行并被其结果替换。

回答by codaddict

You can do something like;

你可以做类似的事情;

x=$(grep $(dirname "$path") file)

here dirname "$path"will run first and its result will be substituted and then grep will run, searching for the result of dirnamein the file

这里dirname "$path"将首先运行,它的结果将被替换,然后grep的运行,搜索结果dirnamefile