Wednesday, May 1, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 11678  / 2 Years ago, wed, february 2, 2022, 6:15:43

I am following this bash shell scripting guide:





In the section Numeric Comparisons, it cites an example:



anny > num=`wc -l work.txt`

anny > echo $num
201

anny > if [ "$num" -gt "150" ]
More input> then echo ; echo "you've worked hard enough for today."
More input> echo ; fi


What seems to happen above is we store a string of commands in a bash variable and then we invoke echo on the variable. What seems to happen is the string is evaluated and the wc command is executed and returns the line count to the controlling terminal.



Ok, so I launch my terminal in Ubuntu 12.04 and try something similar:



$ touch sample.txt && echo "Hello World" > sample.txt
$ cat sample.txt
Hello World
$ num='wc -l sample.txt'
echo $num
wc -l sample.txt


Wait a second, that didn't evaluate the string and return the line count. That just echoed the string back to the terminal. Why did I get different results?


More From » command-line

 Answers
2

You need to use backticks to evaluate the expression.



$ num=`wc -l sample.txt`
$ echo $num
1 sample.txt


If you want to see only "1" in the output, use the command



$ num=`cat sample.txt | wc -l`
$ echo $num
1


And also works:



$ num=`wc -l < sample.txt`
$ echo $num
1


For additional information, see Differences between doublequotes " ", singlequotes ' ' and backticks ´ ´ on commandline?


[#26475] Friday, February 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
edseager

Total Points: 185
Total Questions: 105
Total Answers: 102

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;