13

For example, I have been trying to say "There are 10 people online at the moment" in my script file.

I can never seem to get the command working without the "people online at the moment" part on the next line.

At the moment, I have

w='who | wc -l' 
echo "There are $w people online at the moment" 

However, I always end up with the output

There are who | wc -l users online at the moment 

How do you get the command working in the middle? I've been trying to look and copy examples, but it doesn't seem to help my command substitution issue.

Anthon
  • 79,293
techiegeek
  • 259
  • 1
  • 2
  • 6

3 Answers3

20

You want the output of

who | wc -l

assigned to w, not that string, which is what you get because of the quotes around it. You should use command substitution $(...):

w=$(who | wc -l)
echo "There are $w people online at the moment"

(you can also use the backquotes, but you cannot easily nest those).

Anthon
  • 79,293
  • In some shells, including Bash, you can nest backquotes. It requires nested escapes, see example at http://stackoverflow.com/a/2657037/776723 – ShadSterling Dec 13 '14 at 07:57
  • 1
    @Polyergic Thanks. I updated my answer, but I think I will stick with nesting $() myself ;-) – Anthon Dec 13 '14 at 09:31
10

Another solution:

echo There are $(who | wc -l) people online at the moment

Sreeraj
  • 5,062
6

you should use backtick to execute command

w=`who | wc -l` echo "There are $w people online at the moment"

Jenny D
  • 13,172
Security Beast
  • 902
  • 7
  • 14