bash 如何在shellscripting中将命令结果存储在变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19951369/
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
How to store command results in a variable in on shellscripting?
提问by Rahul KP
I want to find out number of directories and files in home directory and want to store count some variable in a shell script. I am using following set of commands.
我想找出主目录中目录和文件的数量,并想在 shell 脚本中存储一些变量。我正在使用以下命令集。
command="ls -l | grep -c \"rahul.*patle\""
eval $command
i want to store this count into some varibale count. How can i do this.
我想将此计数存储到一些可变计数中。我怎样才能做到这一点。
回答by fedorqui 'SO stop harming'
The syntax to store the command output into a variable is var=$(command)
.
将命令输出存储到变量中的语法是var=$(command)
.
So you can directly do:
所以你可以直接这样做:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
变量$result
将包含匹配的数量。