bash 将命令的输出分配给变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20688552/
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-09-10 00:33:42  来源:igfitidea点击:

Assigning the output of a command to a variable

bashunixsh

提问by user3114665

I am new with unix and I am writing a shell script.

我是 unix 新手,正在编写一个 shell 脚本。

When I run this line on the command prompt, it prints the total count of the number of processes which matches:

当我在命令提示符下运行这一行时,它会打印匹配的进程数的总数:

ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'

example, the output of the above line is 2 in the command prompt.

例如,上面一行在命令提示符下的输出是 2。

I want to write a shell script in which the output of the above line (2) is assigned to a variable, which will be later be used for comparison in an if statement.

我想编写一个 shell 脚本,其中将上述第 (2) 行的输出分配给一个变量,该变量稍后将用于在 if 语句中进行比较。

I am looking for something like

我正在寻找类似的东西

output= `ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'`
echo $output

But when i run it, it says output could not be found whereas I am expecting 2. Please help.

但是当我运行它时,它说找不到输出,而我期待 2。请帮忙。

回答by Marutha

You can use a $sign like:

您可以使用以下$标志:

OUTPUT=$(expression)

回答by Jed Daniels

Try:

尝试:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( )tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

包装您的命令会$( )告诉 shell 运行该命令,而不是尝试将命令本身设置为名为“output”的变量。(请注意,您也可以使用反引号 `command`。)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.htmlto learn more about command substitution.

我强烈推荐http://tldp.org/LDP/abs/html/commandsub.html以了解有关命令替换的更多信息。

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

此外,正如 1_CR 在评论中正确指出的那样,等号和赋值之间的额外空格导致它失败。这是我的机器上您遇到的行为的一个简单示例:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

回答by Jahid

If you want to do it with multiline/multiple command/s then you can do this:

如果你想用 multiline/multiple command/s 来做,那么你可以这样做:

output=$( bash <<EOF
#multiline/multiple command/s
EOF
)

Or:

或者:

output=$(
#multiline/multiple command/s
)

Example:

例子:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

输出:

first
second
third