Bash unbound variable

Viewed 5810

I got a script that has this in there :

su - jenkins sh -c "ps xu | grep sneakers | grep -v grep | awk '{print $2}' | xargs -r kill"

This is the error I get:

line 10: $2: unbound variable

I thought I can solve this by changing this set -eu to set -e at the top of my script. But removing by u I got different type of error :

kill: invalid argument c

Usage:
 kill [options] <pid> [...]

Options:
 <pid> [...]            send signal to every <pid> listed
 -<signal>, -s, --signal <signal>
                        specify the <signal> to be sent
 -l, --list=[<signal>]  list all signal names, or convert one to a name
 -L, --table            list all signal names in a nice table

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see kill(1).

I am not starting my script here with any arguments, but also the awk part should be local not global (I don't understand bash scopes that well if you can't tell).

How do I go about solving this issue?

2 Answers

I got a script that has this in there :

blabalabl "blabla $2 blabla "

Sure - $2 is inside double quotes, so it's getting expanded. The same way:

echo "$2"

expands $2. The solution is to escape $2 expansion.

sh -c "ps xu | grep sneakers | grep -v grep | awk '{print \$2}' | xargs -r kill"

But the whole line is just bad. Do not ps | grep | grep -v grep - use pgrep for that. And to kill on linux you may just:

su - jenkins pkill sneakers

I suggest you use pkill -f sneakers command.

su - jenkins sh -c "pkill -f sneakers"

It is simaplr and cleaner. If it fails add -9 signal.

su - jenkins sh -c "pkill -9 -f sneakers"
Related