for loop to get more than one arguments

9,541

Solution 1

You might also use an arithmetic for loop like this:

a=(user1 pass1 user2 pass2)
for ((i=0; i<${#a[@]}; i+=2)); do
  echo "${a[i]}: ${a[i+1]}"
done

Solution 2

In bash, you can create an array, but nested data structures are not supported. Therefore, you have to hack something yourself. For example, you can use a separator:

#! /bin/bash
for tuple in user1#pass1 user2#ls\;ls user3#pass#3 ; do
    user=${tuple%%#*}
    password=${tuple#*#}
    echo User $user
    echo Password $password
done

Just make sure the first value never contains the separator.

Or, use set with a flat list and shift the right number of members in each iteration:

#! /bin/bash
set -- user1 pass1 user2 ls\;ls user3 pass#3
while (( $# )) ; do
    user=$1
    password=$2
    shift 2
    echo User $user
    echo Password $password
done
Share:
9,541

Related videos on Youtube

Mohammad Etemaddar
Author by

Mohammad Etemaddar

Open Source feels open to the world.

Updated on September 18, 2022

Comments

  • Mohammad Etemaddar
    Mohammad Etemaddar over 1 year

    In python and some other programming languages, it is easy to get a vector instead of one variable everywhere and in loops. like python:

    for variable in [[user1,pass1],[user2,pass2],[user3,pass3],...]
        print variable[0]
        print variable[1]
    

    But how can I get two arguments in one cycle, in shell?

  • manatwork
    manatwork almost 11 years
    As labeled bash, you can use the C-like for to avoid messing with $@: pastebin.com/Ygy3Cs0C
  • manatwork
    manatwork almost 11 years
    Your [[ $1 ]] condition will fail to loop to the end if you have an empty odd value, like set -- user1 pass1 '' ls\;ls user3 pass#3. Better use (($#)) instead.
  • manatwork
    manatwork almost 11 years
    Regarding the eval, is better to avoid it when possible. Either by using user="${tuple%%#*}"; password="${tuple#*#}" or by using IFS='#' read user password <<< "$tuple".
  • matt_in_themuk
    matt_in_themuk over 8 years
    the above is a perl hash and the one liner simply loops thru the hash and prints the contents. Looks like the "$_" did not get printed, but in perl it's a special variable - The default input and pattern-searching space. perldoc.perl.org/perlvar.html#General-Variables