35

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.

banan3'14
  • 3,810
  • 3
  • 24
  • 47
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159
  • Possible duplicate of [How to set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-of-a-command-in-bash) – codeforester Oct 19 '18 at 23:40

3 Answers3

74

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

#!/bin/bash
some_var=$(grep -c "some text" /tmp/somePath)
echo "var value is: ${some_var}"
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • 1
    Thanks, for answer. But how to use input variable in executable part of code? my_var=$(grep "word" $1) - not works – Sonique Dec 03 '15 at 13:49
36


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.

JavaSheriff
  • 7,074
  • 20
  • 89
  • 159
3
some_var=$(grep -c "some text" /tmp/somePath)

From 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.
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175