bash 将 grep 计数分配给变量

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

Assign grep count to variable

bashshellgrep

提问by JavaSheriff

How to assign the result of

如何分配结果

grep -c "some text" /tmp/somePath

into variable so I can echo it.

变成变量,所以我可以回应它。

#!/bin/bash
some_var = grep -c "some text" /tmp/somePath
echo "var value is: ${some_var}"

I also tried:

我也试过:

some_var = 'grep -c \"some text\" /tmp/somePath'

But I keep getting: command not found.

但我不断得到:command not found

回答by that other guy

To assign the output of a command, use var=$(cmd)(as shellcheckautomatically tells you if you paste your script there).

要分配命令的输出,请使用var=$(cmd)(因为shellcheck 会自动告诉您是否将脚本粘贴到那里)。

#!/bin/bash
some_var=$(grep -c "some text" /tmp/somePath)
echo "var value is: ${some_var}"

回答by JavaSheriff


Found the issue
Its the assignment, this will work:


发现问题
它的分配,这将工作:

some_var=$(command)


While this won't work:


虽然这行不通:

some_var = $(command)


Thank you for your help! I will accept first helpful answer.


感谢您的帮助!我会接受第一个有用的答案。

回答by Lev Levitsky

some_var=$(grep -c "some text" /tmp/somePath)

From man bash:

来自man bash

   Command substitution allows the output of a command to replace the com‐
   mand name.  There are two forms:

          $(command)
   or
          `command`

   Bash performs the expansion by executing command and replacing the com‐
   mand substitution with the standard output of  the  command,  with  any
   trailing newlines deleted.