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
Related videos on Youtube
Comments
-
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 almost 11 years
-
manatwork almost 11 yearsYour
[[ $1 ]]
condition will fail to loop to the end if you have an empty odd value, likeset -- user1 pass1 '' ls\;ls user3 pass#3
. Better use(($#))
instead. -
manatwork almost 11 yearsRegarding the
eval
, is better to avoid it when possible. Either by usinguser="${tuple%%#*}"; password="${tuple#*#}"
or by usingIFS='#' read user password <<< "$tuple"
. -
matt_in_themuk over 8 yearsthe 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