Patils Patils - 1 year ago 73
Bash Question

How to reference multiple string values in array in Shell script

I am trying to store multiple string in for loop but it giving me unwanted answer.
My code is :

declare -a arr=("ps -ef | grep icsmpgum | grep $USER | grep -v grep | awk '{print $9,$8}' | awk '{print $1}'")

for i in "${arr[@]}"
echo "$i"

The output of

ps -ef | grep icsmpgum | grep $USER | grep -v grep | awk '{print $9,$8}' | awk '{print $1}'

is :


I want to refer to these 3 string values in for loop but after applying for loop as mention above it giving me output as :

Output :

ps -ef | grep icsmpgum | grep tsaprm1 | grep -v grep | awk '{print ,}' | awk '{print }'

How should I store these string values in variables ?

Answer Source

You need to use a command substitution, rather than quoting the command:

arr=( $(ps -ef | grep icsmpgum | grep $USER | grep -v grep | awk '{print $9,$8}' | awk '{print $1}') )

I suspect that this will work but there's a lot of further tidying up to be done; all the filtering that you want to do is possible in one call to awk:

arr=( $(ps -ef | awk -v user="$USER" '!/awk/ && /icsmpgum/ && $0 ~ user { print $9 }') )

As mentioned in the comments, there are potential risks to building an array like this (e.g. glob characters such as * would be expanded and you would end up with extra values in the array). A safer option would be to use a process substitution:

read -ra arr < <(ps -ef | awk -v user="$USER" '!/awk/ && /icsmpgum/ && $0 ~ user { print $9 }')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download