I try to convert one command line output into a (or store into a ) variable. The command is
ps -U root u | grep ruby | wc -l
The output is 1, but when I use
$(ps -U root u | grep ruby | wc -l)
the output is
1: command not found
Here,
$(ps -U root u | grep ruby | wc -l)
You are not saving the output into a variable. So the shell attempts to execute the result (which happens to be 1
in your case). Since it couldn't find a command/function named 1
, you get the error.
You probably want:
output=$(ps -U root u | grep ruby | wc -l)
Now, output
will have 1
which you can print with:
echo "${output}"
Btw, grep
can count itself using the -c
option. So wc
is unnecessary here:
output=$(ps -U root u | grep -c ruby)
echo "${output}"
In the latter case, the command inside the $(…)
is evaluated and the result is then used to create a new command, which the shell then tries to execute. Since there is no command or program named 1
, you get the message you are seeing. It easier to see what's happening if you writer echo Result: $(ps -U root u | grep ruby | wc -l). your output would be Result: 1
.
To assign to a variable do it like this, using backtics
a=`ps -U root u | grep ruby | wc -l`