bash

Apply actions over selected elements in a list in bash


I have a bash script which has 4 elements, and I want to loop over the last 2. So I tried this:

#!/usr/bin/env bash
arg1=$1
arg2=$2
arg3=$3
arg4=$4
list_total=( "$3 $4" )

for my_element in "${list_total}"; do
    echo "$my_element"
    echo "Wow"
done

When running it with sh myscript.sh Joe Jack Jim Jess the output is:

Jim Jess
Wow

But it's not what I intended with the script. I want to output:

Jim
Wow
Jess
Wow

Please, could you point out what I am doing wrong?


Solution

  • You will need to create the list_total array with separate elements instead of a single string. To do this, change the line list_total=( "$3 $4" ) to list_total=( "$3" "$4" ). Something like:

    #!/usr/bin/env bash
    arg1=$1
    arg2=$2
    arg3=$3
    arg4=$4
    list_total=( "$3" "$4" ) # <--- Here
    
    for my_element in "${list_total[@]}"; do
        echo "$my_element"
        echo "Wow"
    done
    

    Alternative to this incase if you're looking:

    Shell parameter expansion

    #!/usr/bin/env bash
    # Directly access the script's arguments
    for ((i = 3; i <= 4; i++)); do
      my_element="${!i}"
      echo "$my_element"
      echo "Wow"
    done
    

    SAMPLE DEMO