0

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

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

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

The output of

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

is :

icsmpgum     
ABC
DEF

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 ?

1 Answer 1

1

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 }')
Sign up to request clarification or add additional context in comments.

1 Comment

This will make the output from the command substitution undergo pathname expansion - which might not be a problem - but to be safe one could use read -ra arr < <(ps ....)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.