Home > Mobile >  How to make loop which depends of number from variable
How to make loop which depends of number from variable

Time:12-24

I tried so much to do this, but I still don't know to write it property.

Example:

I have someVariable which contain words.

someVariable="Otter HoneyBadger Seal"

Depending on the number of Strings located in someVariable I need to make a visual list with echo.

I had this idea:


someVariable="Otter HoneyBadger Seal"
someVariable_number="echo $someVariable | wc -w"

while true
    do
        j=1
        if [[ ${j} -gt ${someVariable_number} ]]; then
            echo $someVariable | awk '{ print $j }'
            ((j  ))
        fi
    done

Apart from the stylistics that I did not include, would like the output to look like this

./someScript
#OUTPUT
[1] Otter
[2] HoneyBadger
[3] Seal

CodePudding user response:

With bash:

someVariable="Otter HoneyBadger Seal"

for i in $someVariable; do echo "[$((  c))] $i"; done

Output:

[1] Otter
[2] HoneyBadger
[3] Seal

CodePudding user response:

Use an array. It will be simpler and faster and safer.

# read the words of the variable into an array
read -ra words <<<"$someVariable"

# iterate over the array indices
for idx in "${!words[@]}"; do
    printf '[%d] %s\n' $((idx   1)) "${words[idx]}"
done
[1] Otter
[2] HoneyBadger
[3] Seal

Safer because you don't have any unquoted variables. Try other techniques with

someVariable="Otter HoneyBadger Seal *"

and see how many you get

CodePudding user response:

Addressing just the issues with OP's current code ...

A few issues...

# wrong: assigns string to variable

$ someVariable_number="echo $someVariable | wc -w"
$ echo "${someVariable}"
echo Otter HoneyBadger Seal | wc -w

# right: executes 'echo|wc' and saves result to variable

$ someVariable_number=$(echo $someVariable | wc -w)
$ echo "${someVariable}"
3

Infinite loop since j=1 will never be -gt 3 so the echo|awk;j is never executed and loop will run forever; also, each pass through loop you are resetting j=1 effectively wiping out the j ; last issue is the incorrect usage of a bash variable inside an awk script:

# wrong:

while true
do
    j=1
    if [[ ${j} -gt ${someVariable_number} ]]; then 
        echo $someVariable | awk '{ print $j }'
        ((j  ))
    fi
done

# right: consolidate `while` and `if`

j=1
while [[ "${j}" -le "${someVariable_number}" ]]
do
    echo "${someVariable}" | awk -v field_no="${j}" '{print "[" field_no "] " $field_no}'
    ((j  ))
done

# better (?):

myarray=( dummy_placeholder ${someVariable} )

for ((j=1; j<=${someVariable_number}; j  ))
do
    printf "[%d] %s\n" "${j}" "${myarray[j]}"
done
     

Which generates:

[1] Otter
[2] HoneyBadger
[3] Seal

NOTE: see Cyrus' answer for one idea on streamlining the code

  •  Tags:  
  • bash
  • Related