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?

3 Answers 3


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]}"

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
    echo User $user
    echo Password $password

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
    shift 2
    echo User $user
    echo Password $password
  • As labeled bash, you can use the C-like for to avoid messing with $@: pastebin.com/Ygy3Cs0C
    – manatwork
    Jun 14, 2013 at 9:55
  • 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
    Jun 14, 2013 at 9:57
  • 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".
    – manatwork
    Jun 14, 2013 at 10:03

I like perl for this stuff, you can call this from inside a bash script:

perl -e 'my %users= ("user1" => "pass1","user2" => "pass2");
         for ( sort keys %users)
             print "$_\t$users{$_}\n";
  • 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 Sep 24, 2015 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.