user1224398
user1224398

Reputation: 125

bash write a loop to run a command

The problem is like this:

There is a script called run, I need to change the operation of run to make the 2nd field of the output of run to be 0 (Please note: it's not the output of run but a part of it). I just don't know how to judge the value of the the 2nd field of the output of run for a loop.

Does anyone have any good ideas? Thank you.

Upvotes: 2

Views: 119

Answers (2)

user unknown
user unknown

Reputation: 36229

Capture the output of run in an array and modify the second element like this:

res=($(echo 1 2 3 4))
# show whole array
echo ${res[@]}
1 2 3 4
# show element 2 with index 1:
echo ${res[1]}
2
# modify second element:
res[1]=0
# verify modified element:
echo ${res[1]}
0
# verify whole thing:
echo ${res[@]}
1 0 3 4

so for your command:

res=($(run))
res[1]=0
# usage of manipulated result:
echo ${res[@]}

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185015

See this snippet :

out=$(command | awk '{print $2}')
((out)) || echo "zero detected"

or simply:

command | awk '($2 == 0) {print "zero detected"}'

On in a for loop :

command | while read a b c d; do
    ((b)) || echo "zero detected"
done

note: ((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed. See http://mywiki.wooledge.org/ArithmeticExpression

Upvotes: 3

Related Questions