34

如何分配结果

grep -c "some text" /tmp/somePath

进入变量,以便我可以回显它。

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

我也试过:

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

但我不断得到:command not found

4

3 回答 3

69

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

#!/bin/bash
some_var=$(grep -c "some text" /tmp/somePath)
echo "var value is: ${some_var}"
于 2013-05-01T22:18:15.663 回答
32


找到问题
它的任务,这将工作:

some_var=$(command)


虽然这不起作用:

some_var = $(command)


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

于 2013-05-01T22:22:00.457 回答
3
some_var=$(grep -c "some text" /tmp/somePath)

来自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.
于 2013-05-01T22:18:03.333 回答