JavaSheriff
JavaSheriff

Reputation: 7687

Assign grep count to variable

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.

Upvotes: 35

Views: 96085

Answers (3)

that other guy
that other guy

Reputation: 123750

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}"

Upvotes: 74

JavaSheriff
JavaSheriff

Reputation: 7687


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.

Upvotes: 36

Lev Levitsky
Lev Levitsky

Reputation: 65871

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.

Upvotes: 3

Related Questions