开发者

variable still empty after the loop problem in shell scripting

I'm very new in shell scripting, and I encountered a problem that is quite wired. The program is rather simple so I just post it here:

#!/bin/bash

list=""

list=`mtx -f /dev/sg2 status | while read status
do
    result=$(echo ${status} | grep "Full")
    if [ -z "$result" ]; then
        continue
    else
       echo $(echo ${result} | cut -f3 -d' ' | tr -d [:alpha:] | tr -d [:punct:])
    fi
done`

echo ${list}

for haha in ${list}
do
    printf "current slot is:%s \n" ${haha}
done

What the program does is that it executes mtx -f /dev/sg2 status and goes to each line and see if there's a full disk. If it has "Full" in that line, I'll record the slot number in that line, and put in the list.

Notice that I put a back quote after list= at line 6, and it covers the whole "while" loop after that. The reason is unclear to me, but I got this usage by just googling it. It is said that the while loop will open up a separate shell or something like that, so when the while loop is done, whatever you concatenated in the loop will get lost, so in my initial implementation开发者_如何学编程, list is still empty after the while loop.

My question is: even if the code above works fine, it looks pretty tricky to others, and what's worse, I can only make only ONE list after the loop is done. Is there a better way to fix this so that I can pull out more information from the loop? Like what if I need list2 to store other values? Thanks.


Your shell script does work. If you wanted to get two pieces of info per line insteal of one, you would have to change this line

echo $(echo ${result} | cut -f3 -d' ' | tr -d [:alpha:] | tr -d [:punct:])

to concatenate the desired values separated by a comma or any other "special" character. Then you could parse your list this way :

for haha in ${list}
do
   printf "current slot is:%s, secondary info:%s \n" $(echo ${haha} | cut -f1 -d',') $(echo ${haha} | cut -f2 -d',')
done


See this explanation. As a pipe is involved, the while read... code isn't executed in your current shell, but in a subshell (A child process which can't update your current process' (environment/shell) variables).

Choose on of the listed workarounds to make the while read... loop execute in your current shell.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜