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 ?
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.
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.
$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.
In awk we access fields using syntax like: $1 or $2. $1 indicates that you are referring to the first field or first column.
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}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With