简体   繁体   中英

bash / Variable value is empty after the loop

I'm new to bash and try a simple loop but the value of my variable is being lost after it and I can not understand why - I have looked at few similar issues but they are all related to subshell execution of a while loop . I'm not doing but still facing issues - can someone explain me where is my mistake ?

#!/bin/bash

check_ss ()    
{    

command_list | awk '{print $1 $9}' > ss.out    

 for i in {1..8}    
            do grep -Pa "\x3$i" ss.out > ss$i.out   
                    if grep -w "NotStarted" ss$i.out   
                            then   
                                   ss$i=0   
                            else    
                                ss$i=1    
                    fi   
done   
}   
check_ss      
echo $ss1     
echo $ss2    
echo $ss3    
echo $ss4    

I'm getting this on execution :

[root@lubo ~]# ./ss.sh    
./ss.sh: line 21: ss1=1: command not found     
./ss.sh: line 21: ss2=1: command not found      
./ss.sh: line 21: ss3=1: command not found      
./ss.sh: line 21: ss4=1: command not found      
./ss.sh: line 21: ss5=1: command not found      
./ss.sh: line 21: ss6=1: command not found     
./ss.sh: line 21: ss7=1: command not found     
./ss.sh: line 21: ss8=1: command not found   

Thanks in advance

您需要使用declare来动态构造变量名。

declare "ss$i=0"

An array would be a better alternative to dynamic variable names.

check_ss() {
    ss=()
    command_list | awk '{print $1 $9}' > ss.out

    for i in {1..8}; do
        grep -Pa "\x3$i" ss.out > ss$i.out
        if grep -w "NotStarted" ss$i.out; then
            ss[$i]=0
        else
            ss[$i]=1
        fi
    done
}

check_ss      
echo ${ss[1]}
echo ${ss[2]}
echo ${ss[3]}
echo ${ss[4]}

You could also get rid of the temporary files.

check_ss() {
    ss=()
    command_list | awk '{print $1 $9}' > ss.out

    for i in {1..8}; do
        if grep -Pa "\x3$i" ss.out | grep -w "NotStarted"; then
            ss[$i]=0
        else
            ss[$i]=1
        fi
    done
}

I don't know what your input looks like exactly, but you might even be able to simplify it further to something like:

check_ss() {
    ss=()
    while read i; do
        ss[$i]=1
    done < <(command_list | awk '$9=="NotStarted" {print $1}')
}

or if you just want a list of the NotStarted numbers,

ss=(command_list | awk '$9=="NotStarted" {print $1}')
echo "${ss[@]}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM