bash 将输出存储在变量中并在命令中使用变量

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

Store output in variable & use variable in command

linuxbashshellunixterminal

提问by ojhawkins

I am trying to run a command and store it in a variable.

我正在尝试运行一个命令并将其存储在一个变量中。

length=`last | grep foouser | wc -l` 

It works fine but when I add a variable to the command it breaks.

它工作正常,但是当我向命令添加变量时,它会中断。

value=
length=`last | grep $value | wc -l`

How can I get this second example to work by acceptomg a variable?

如何通过接受变量来使第二个示例工作?

回答by Benoit

You should quote your variables properly. If they contain spaces your script might break:

您应该正确引用您的变量。如果它们包含空格,您的脚本可能会中断:

value=""
length="$(last | grep "$value" | wc -l)"

回答by glenn Hymanman

You don't actually need wc:

你实际上并不需要wc

length=$(last | grep -c "$value")

You could improve the variable names

您可以改进变量名称

num_logins=$(last | grep -c "$username")