0

cmd is an array, I wanted to grep each index:

for i in "${cmd[@]}";
do
a=`deep status | grep "${cmd[$i]}" |  awk  '{print $2 ~ /RUNNING/}'

But this is not working a should contain either 1 or 0, but I am getting no process:

cmd[@]: ERROR (no such process)
4
  • Welcome to SO, please edit your question and use "Code Sample" for greater readability. Commented Jun 8, 2019 at 8:13
  • The code is too incomplete to evaluate. The a variable has no closing backtick, and there's no done statement. What does deep do? Commented Jun 8, 2019 at 9:05
  • 1
    Add a shebang and then paste your script there: shellcheck.net Commented Jun 8, 2019 at 9:06
  • 1
    Your question appears to be an XY Problem. See: What is the XY problem?. Posting the actual information with input and output would likely result in a better proposed solution that would likely eliminate one or both pipes and the loop. Commented Jun 8, 2019 at 18:47

1 Answer 1

1

You're iterating over the contents of the array then trying to use the element as an index. You need to use the element directly as the argument:

for i in "${cmd[@]}"
do
    a=$(deep status | awk -v my_var="$i" '$0 ~ my_var {print $2 ~ /RUNNING/}')
done

It is possible to iterate over the indices, then use the index in the array reference, but this is probably not necessary unless you need to do something with the indices themselves:

for i in "${!cmd[@]}"    # Note the "!"
do
    echo "$i"    # or some other operation using the index
    a=$(deep status | awk -v my_var="${cmd[$i]}" '$0 ~ my_var {print $2 ~ /RUNNING/}')
done

Note that it's not necessary to pipe grep into awk since the latter can do the the matching itself. I have used $0 here, but you can be more specific if you know which field you're trying to match.

Also, repeatedly running the same command in a loop can be slow. Depending on how "deep status" works and the format of your array, you may be able to do the whole thing without the for loop.

And use $() instead of backticks. They're much more readable and more easily nested.

Sign up to request clarification or add additional context in comments.

2 Comments

you can improve the awk script with: awk "/${cmd[$i]}/{print \$2 ~ /RUNNING/}"
@DudiBoy: That's not an improvement. It is better to pass variables into AWK using the -v option.

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.