zlobul
zlobul

Reputation: 375

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

Upvotes: 1

Views: 2421

Answers (2)

John Kugelman
John Kugelman

Reputation: 361585

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[@]}"

Upvotes: 2

chepner
chepner

Reputation: 531055

You need to use declare to dynamically construct a variable name.

declare "ss$i=0"

Upvotes: 5

Related Questions