How to use param values inside for loop Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to use param values inside for loop without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am running my script as script.sh 12345 12346 12347

for z in 1..$(seq 1 $#);
do
    echo "param $z is $($(echo $z))"; //Line 4
done;

I am expecting output as below:

param 1 is 12345
param 2 is 12346
param 3 is 12347

Guess, I am missing something in Line 4.

Answer

The problem with $($(echo $z)) is that it expands, first to $(1) (if $z is 1) and then the shell tries to run 1 as a command.


Assuming bash:

params=( "$@" )

for (( i = 0; i < ${#params[@]}; ++i )); do
    printf 'Param %d is "%s"n' "$i" "${params[i]}"
done

Running it:

$ bash script.sh a b c
Param 0 is "a"
Param 1 is "b"
Param 2 is "c"

Or, with /bin/sh:

i=0
while [ "$#" -gt 0 ]; do
    printf 'Param %d is "%s"n' "$i" "$1"
    i=$(( i + 1 ))
    shift
done

Running that:

$ /bin/sh script.sh a b c
Param 0 is "a"
Param 1 is "b"
Param 2 is "c"

That’s if you really need to explicitly enumerate them. Usually one would just loop over "$@":

for param in "$@"; do
    printf 'Param: "%s"n' "$param"
    # do other thing with "$param" here
done
We are here to answer your question about How to use param values inside for loop - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji