Evaluating a string in shell script
Solution 1:
Please note that symbol:
'
Single quote
Enclosing characters in single quotes preserves the literal value of
each character within the quotes. A single quote may not occur between
single quotes, even when preceded by a backslash.
and
`
Backquote
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.
So the Backquote is returning result of the command to Standard Output. That is why
`wc -l sample.txt`
returns results of the command, while
'wc -l sample.txt'
just return "wc -l sample.txt" as usual string
Consider doing this as example:
$ A='wc -l /proc/mounts'
$ B=`wc -l /proc/mounts`
$ C=$(wc -l /proc/mounts)
And now echo all three variables:
$ echo $A
wc -l /proc/mounts
$ echo $B
35 /proc/mounts
$ echo $C
35 /proc/mounts
Solution 2:
If you want to capture the output of a command in a variable, you need to either use backticks ``
or enclose the command in $()
:
$ d=$(date)
$ echo "$d"
Mon Mar 17 10:22:25 CET 2014
$ d=`date`
$ echo "$d"
Mon Mar 17 10:22:25 CET 2014
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 $()
:
$ echo $(date -d $(echo yesterday))
Sun Mar 16 10:26:07 CET 2014
See this thread on U&L for some more details of why ``
should be avoided.
Solution 3:
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?