how can we use multiple variables in single for loop in shell script
Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
You could do it by cycling through a pair of arrays:
Code:
#!/bin/bash
# Define the arrays
array1=("a" "b" "c" "d")
array2=("w" "x" "y" "z")
# get the length of the arrays
length=${#array1[@]}
# do the loop
for ((i=0;i<=$length;i++)); do
echo -e "${array1[$i]} : ${array2[$i]}"
done
Code:
~ $ ./tmp.sh
a : w
b : x
c : y
d : z
Although a more skilled bash-ist will probably have a better way...
A conversation with an associate (LQ user fukawi2) informed me that you can convert a space delimited string with:
Code:
array1=(${ch1// / })
array2=(${ch2// / })
so the example would look like:
Code:
#!/bin/bash
ch1="a b c d"
ch2="w x y z"
# Define the arrays
array1=(${ch1// / })
array2=(${ch2// / })
# get the length of the arrays
length=${#array1[@]}
# do the loop
for ((i=0;i<=$length;i++)); do
echo -e "${array1[$i]} : ${array2[$i]}"
done
The array is set by breaking up the input string into words. Words are defined by whitespace (space+tab+newline) by default, so you don't need to do anything special in this case.
Code:
array1=( $ch1 )
Now if the input strings were delimited by a different character, then you can use a substitution to convert them to spaces for word-breaking.
Code:
ch1='a:b:c:d'
array1=( ${ch1//:/ } )
However, if the individual entries themselves include whitespace, then this won't work. They'll be broken up as well. You need to change the default delimiter, the IFS variable, so that it ignores whitespace and only divides on the character you want.
This is a convenient method because when (most) commands are directly prefixed by a variable setting (not separated by a command terminator), then that setting only affects the invoked command. So we don't need to back up or restore the original IFS setting.
Edit: I just want to add, arrays are certainly the way to go. Any time you have multiple related strings (i.e. lists of entries), you should start by storing them in an array, rather than a scalar variable. This way you can avoid having to break them up later.
Last edited by David the H.; 11-11-2011 at 03:00 PM.
Reason: fixed formatting + minor rewording
Hello Negendar you can use this code, is this case you wont need to use arrays;
#!/bin/bash
ch1="a b c d"
ch2="w x y z"
i=0
IFS=" "
for ch in $ch1; do
echo ${ch1:$i:1} ${ch2:$i:1}
(( i+=2 ))
done
Thanks ahh bra
That will break as soon as the inputs are no longer a set of single characters with single character delimiters. In other words, it will break as soon as he tries to run it with anything other than the grossly simplified example in the OP.
That will break as soon as the inputs are no longer a set of single characters with single character delimiters. In other words, it will break as soon as he tries to run it with anything other than the grossly simplified example in the OP.
That's pretty much evident, but I don't see OP asking a generalized solution or indicating that inputs are going to be different. Perhaps he really wanted to work with that string?
@Michael22Orr:
How is your code different than what i posted? Just curious
By the way, in bash at least, there's a more compact way to iterate through an array.
Code:
for i in "${!array1[@]}"; do
echo "${array1[i]} : ${array2[i]}"
done
${!array[@]} outputs a list of all existing array indexes. This is especially useful with sparse arrays (arrays with missing elements) and associative arrays (which use strings as indexes).
So the above is all you need as long as array2 has exactly the same indexes as array1.
The method that I use is a little more old fashioned, but I think it is clearer to understand and is portable across shells...
Just pass the 'for' loop a list of delimited values and then split them up inside your loop.
Code:
for KeyValPair in 'a,w' 'b,x' 'c,y' 'd,z'
do
i=`echo "$KeyValPair" | cut -d',' -f1`
j=`echo "$KeyValPair" | cut -d',' -f2`
echo $i:$j
done
Here's another example:
Code:
for NamePair in 'John,Smith' 'Jane,Doe' 'Betty,Doe-Smith' 'Madonna,'
do
FirstName=`echo "$NamePair" | cut -d',' -f1`
LastName=`echo "$NamePair" | cut -d',' -f2`
echo "First: $FirstName Last: $LastName"
done
You must use a delimiter that should never appear in your data. If I had used a dash delimiter, then item #3 would have been 'Betty-Doe-Smith' resulting in a LastName of just 'Doe', which is incorrect. If you use single quotes for each data pair (or triplet, or quaqruplet, etc.) then you can use more exotic characters like a pipe symbol: 'Betty|Doe-Smith'
Note that this technique allows you to have "null" items as in the example for Madonna (who does not have a last name). Just make sure that still include the delimiters.
The method that I use is a little more old fashioned, but I think it is clearer to understand and is portable across shells...
Just pass the 'for' loop a list of delimited values and then split them up inside your loop.
Code:
for KeyValPair in 'a,w' 'b,x' 'c,y' 'd,z'
do
i=`echo "$KeyValPair" | cut -d',' -f1`
j=`echo "$KeyValPair" | cut -d',' -f2`
echo $i:$j
done
Here's another example:
Code:
for NamePair in 'John,Smith' 'Jane,Doe' 'Betty,Doe-Smith' 'Madonna,'
do
FirstName=`echo "$NamePair" | cut -d',' -f1`
LastName=`echo "$NamePair" | cut -d',' -f2`
echo "First: $FirstName Last: $LastName"
done
You must use a delimiter that should never appear in your data. If I had used a dash delimiter, then item #3 would have been 'Betty-Doe-Smith' resulting in a LastName of just 'Doe', which is incorrect. If you use single quotes for each data pair (or triplet, or quaqruplet, etc.) then you can use more exotic characters like a pipe symbol: 'Betty|Doe-Smith'
Note that this technique allows you to have "null" items as in the example for Madonna (who does not have a last name). Just make sure that still include the delimiters.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.