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?
Please note that symbol:
Single quote
and
Backquote
So the Backquote is returning result of the command to Standard Output. That is why
returns results of the command, while
just return "wc -l sample.txt" as usual string
Consider doing this as example:
And now echo all three variables:
If you want to capture the output of a command in a variable, you need to either use backticks
``
or enclose the command in$()
:Note that the string is actually evaluated at the moment of the variable declaration, not when you echo it. The command is actually run within the
$()
or backticks and the output of that command is saved as the variable's value.In general, you should always use
$()
instead of backticks which are deprecated and only around for compatibility reasons and much more limited. You cannot, for example, nest commands within backticks but you can with$()
:See this thread on U&L for some more details of why
``
should be avoided.You need to use backticks to evaluate the expression.
If you want to see only "1" in the output, use the command
And also works:
For additional information, see Differences between doublequotes " ", singlequotes ' ' and backticks ´ ´ on commandline?