Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading