Use bash script $1 argument in awk command Use bash script $1 argument in awk command shell shell

Use bash script $1 argument in awk command


Use awk -v var=val to pass a command line value to awk and use $0 ~ val syntax to compare it using regex:

ps -elf | awk -v arg="$1" '$0 ~ arg && !/awk/ && $5 == 1{print $15}'

Without regex:

ps -elf | awk -v arg="$1" 'index($0, arg) && !/awk/ && $5 == 1{print $15}'


Shell variables are extended only inside double quotes (or no quotes at all) , not single quotes.You could try

ps -elf | awk '/'$1'/&&!/awk/ {if ($5 == 1){print $15}}'

For awk I think anubhavas solution is better, but this also works in similar situations with other tools.


Note: I'm aware that this doesn't address the question in the title; it is a solution to the actual problem presented in the text. The question about awk is answered below.

It's rarely necessary to parse ps output, since you can ask ps to produce whatever fields you desire. Also, you'll find that pgrep is easier to use and more reliable than grepping ps for a process name. pgrep is installed by default on many Linux distros; if it isn't installed on yours, look at the procps-ng homepage for downloads.

pgrep can directly search for processes with a particular parent pid:

pgrep -P 1 "$1"

That will print out a list of process numbers (pids); you can get it to produce process names as well with the -l option:

pgrep -l -P 1 "$1"

If you want the full command-line, you should pass the pids into ps and tell it to just produce the cmd:

pgrep -P 1 "$1" | xargs ps -ocmd=

Or, if you prefer, the PID and the command line:

pgrep -P 1 "$1" | xargs ps -opid=,cmd=

(Leave out the = if you like to see column headers.)


The best way to pass a command-line parameter into an awk script is to set a variable on the command-line. There are two ways to do this:

awk -v arg="$1" 'program' "filename"...awk 'program' arg="$1" "filename"...

The difference between the two is that the first form makes arg available in BEGIN blocks, whereas the second form is interpreted just before awk opens the file, so it is not available in BEGIN blocks but can be redefined different for subsequent files:

awk 'program' arg="value for file1" file1 arg="value for file2" file2