LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   another simple unix scripting question! storing values in variables (https://www.linuxquestions.org/questions/linux-newbie-8/another-simple-unix-scripting-question-storing-values-in-variables-595797/)

christianunix 10-30-2007 09:45 AM

another simple unix scripting question! storing values in variables
 
how can I store the results of commands, for example if wc -l returns 6, how can I store the value into a variable in a unix script? thanks LQ!!

m0rg 10-30-2007 09:55 AM

Try backquotes, e.g.
RESULT=`cat my_file.txt | wc -l`

pwc101 10-30-2007 10:04 AM

or use the $() construct:
Code:

RESULT=$(wc -l my_file.txt)
I find this more readable and easier to debug.
Quote:

Originally Posted by m0rg
RESULT=`cat my_file.txt | wc -l`

That's a UUOC - wc will take a file as input, no need to spawn a separate instance of cat :)

christianunix 10-30-2007 12:54 PM

I do appreciate both of you for your kind response, and pwc is the winner this time!! :) pwc's method worked.

m0rg's method stores "cat file|wc -l" the command into the variable. The content of the variable becomes the "cat file|wc -l" not the result of the command.

Also,

Code:

result=$(cat file|wc -l)
is better than
Code:

result=$(wc -l file)
cat file|wc -l will save 7 into the variable, and wc -l file will save "7 file" into the variable

pwc101 10-30-2007 01:13 PM

Quote:

Originally Posted by christianunix (Post 2942441)
Also,

Code:

result=$(cat file|wc -l)
is better than
Code:

result=$(wc -l file)
cat file|wc -l will save 7 into the variable, and wc -l file will save "7 file" into the variable

In which case, to avoid using a cat command (which can take a very long time on its own), it's better to use the < redirect, which has the parallel advantages of avoiding the filename becoming part of the output and the unnecessary use of cat:
Code:

RESULT=$(wc -l < file)
Also, make sure you use backticks (on my keyboard it's the key above the tab key) _not_ apostrophes or quotes. Backticks have exactly the same effect as $().


All times are GMT -5. The time now is 09:48 AM.