Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash unbound variable

Tags:

bash

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?

like image 970
Echotest Avatar asked Aug 14 '26 12:08

Echotest


1 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
like image 87
KamilCuk Avatar answered Aug 16 '26 07:08

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!