Read the output of a command into a variable

23,827

To answer your direct question, you need to wrap your code in a $() sequence so that its output can be assigned to a variable. Like so:

x=$(your_code_goes_here)

That said, I have a few notes about your one-liner:

  • Why the leading cat *? This seems to be a useless use of cat. You can directly do

    grep pattern *
    

    which still might not be a good idea since the * would match all files and sub-directories in your current directory and grep will throw a warning if you ask it to search in a directory without supplying the -r (recursive) option. Using the * may or may not be suitable depending on your use case.

  • I'm not sure what the wc -l at the end is intended for: cut doesn't print its output on several lines so wc -l (count the number of lines) would always return 1.

Share:
23,827

Related videos on Youtube

baccksash
Author by

baccksash

Updated on September 18, 2022

Comments

  • baccksash
    baccksash over 1 year

    I am making a bash script but I'm totally new and got lost.

    I've made this code

    cat * | grep "|*parameter1*|" | grep "|*parameter2*|" | cut -f 8,11,12,15,21,23,34 -d "|" | wc -l
    

    which works just fine, but I need to read the wc -l output into a variable so I can make an average after that with another bash command. Then, print out that average and make it readable to the user.

    • Rahul Patil
      Rahul Patil almost 11 years
      if you post some input sample, then using awk we can make it better.
    • Rahul Patil
      Rahul Patil almost 11 years
      if just want to count pattern match then use awk '( /\|parameter1\|/ || /\|paramater2\|/ ) { n++;} END{ print n}' input.file
  • baccksash
    baccksash almost 11 years
    You were right, this is what I needed. I used {cat} because I am gonna write the result into a .txt as well. And that's the reason for the {cut} too The {wc -l} in this case is needed because i am searching for logs with a specific pattern.
  • Jeff Hewitt
    Jeff Hewitt almost 11 years
    @baccksash Again, I doubt that wc -l is the right choice here. Maybe if you gives us more information on what you're trying to accomplish, we can help you achieve it in an easier way.