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.

1

3 Answers 3

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}"
1
  • 1
    Thanks, for answer. But how to use input variable in executable part of code? my_var=$(grep "word" $1) - not works
    – Sonique
    Dec 3, 2015 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.

2
  • 1
    Can't vote this up enough... These are the type of answers that make me grateful for SO.
    – Charlie
    Sep 10, 2014 at 9:40
  • 1
    Thanks a lot for this insight. Agree with Charlie. Can't vote this up enough.
    – ayan_2587
    Jun 1, 2015 at 8:21
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.
3
  • 4
    Variable assignments cannot have spaces around the =. May 1, 2013 at 22:20
  • 1
    @michaelb958 You're right. My post was fixed before I noticed the problem. May 1, 2013 at 22:23
  • Lev this was the problem :) May 1, 2013 at 22:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.