Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use bash script $1 argument in awk command

I want to create a bash script that takes an argument and using awk to print if

it's a orphan process :

#find_orphan.sh :

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

Unfortunately I'm having problems in order to render the $1 as a bash argument..

if I run this without using $1 my program will work :

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

I really need to be able to specify the awk search pattern in the bash script argument.

Any help ?

like image 829
user1783757 Avatar asked Jan 22 '15 16:01

user1783757


People also ask

How do I use bash commands in awk?

AWK can be invoked from the command prompt by simply typing awk . On the command line, it is all lower case. This would result in the matching lines from the /etc/passwd file being printed to the command line. This is fairly basic, and we are using the default behavior of printing the matches.

How do you pass command line arguments in awk?

Arguments given at the end of the command line to awk are generally taken as filenames that the awk script will read from. To set a variable on the command line, use -v variable=value , e.g. This would enable you to use num as a variable in your script. The initial value of the variable will be 10 in the above example.

What is $1 in bash script?

$1 is the first command-line argument passed to the shell script. Also, know as Positional parameters. For example, $0, $1, $3, $4 and so on.

What is a $1 awk?

In awk we access fields using syntax like: $1 or $2. $1 indicates that you are referring to the first field or first column.


1 Answers

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}'
like image 171
anubhava Avatar answered Nov 14 '22 21:11

anubhava