How do I store the output of a bash command in a variable?
I am trying to write a simple script to kill a process. I've already read Find and kill a process on one line with bash and regex , so please don't redirect me to this.
This is my code:
LINE=$(ps aux | grep '$1')
PROCESS=$LINE | awk '{print $2}'
echo $PROCESS
kill -9 $PROCESS
I want to be able to run something like
sh kill_proc.sh node
and run it
kill -9 node
But instead I get
kill_process.sh: line 2: User: command not found
I found out that when I enter the log $PROCESS
it is empty. Does anyone know what I am doing wrong?
source to share
PROCESS=$(echo "$LINE" | awk '{print $2}')
or
PROCESS=$(ps aux | grep "$1" | awk '{print $2}')
I don't know why you are getting the error you mentioned. I cannot reproduce it. When you say this:
PROCESS=$LINE | awk '{print $2}'
the shell expands it to something like this:
PROCESS='mayoff 10732 ...' | awk '{print $2}'
(I have shortened the value $LINE
to make this example readable.)
The first subcommand of the pipeline sets a variable PROCESS
; this setup variable command has no output, so it awk
immediately reads EOF and prints nothing. And since each pipeline subcommand runs in a subshell, the parameter PROCESS
only takes place in the subshell, not in the parent shell that the script is running on, so PROCESS
it still isn't set for later commands in your script.
(Note that some versions bash
may execute the last pipeline subcommand in the current shell rather than a subshell, but this does not affect this example.)
Instead of setting PROCESS
into a subshell and not typing anything awk
to standard input, you want to pass the value LINE
to awk
and store the result in PROCESS
the current shell. Therefore, you need to run a command that writes a value LINE
to its standard output and connects that standard output to its standard inputs awk
. A team echo
can do this (or a team printf
, as Chapner noted in his answer).
source to share
You need to use echo
(or printf
) to actually put the value $LINE
on the command's standard input awk
.
LINE=$(ps aux | grep "$1")
PROCESS=$(echo "$LINE" | awk '{print $2}')
echo $PROCESS
kill -9 $PROCESS
No need to use LINE
; you can install PROCESS
with one line
PROCESS=$(ps aux | grep "$1" | awk '{print $2}')
or better, pass grep
:
PROCESS=$(ps aux | awk -v pname="$1" '$1 ~ pname {print $2}')
Finally, don't use kill -9
; it is the last resort for debugging erroneous programs. For any program you don't write kill "$PROCESS"
should suffice.
source to share