473,406 Members | 2,620 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

bash for loop

1,059 1GB
Please someone explain me

Expand|Select|Wrap|Line Numbers
  1. #!/bin/bash
  2.  
  3. ARRAY=("example program" "for test only" "Lets try");
  4.  
  5. ELEMENTS=${#ARRAY[@]};
  6.  
  7. echo $ELEMENTS;
  8.  
  9. for((i=0;i<$ELEMENTS;i++));do
  10. echo ${ARRAY[$i]} # echo ${ARRAY[${i}]}
  11. done
  12.  
I know what i will get by executing this. got this from a website.
But I dont understand how line 3 work.

As well as the for loop required 2 first bracket "((...))".
If I use one first bracket "(..)" it generates error.

Can anyone explain these for me?

Best regards,
Johny
Aug 26 '10 #1
4 3420
Oralloy
988 Expert 512MB
Johny,

bash is a marvelously complex tool. And, it's still evolving, because it's so very useful.

I've got quite a good tutorial book for it at home. It's a bit old, though, like 10 years or so. Still, I wish I could remember the title. It's one of the "Animal" books, though.

Basically you need to use double parentheses because of other aspects of the bash syntax.

Try looking up "bash for loop syntax" on google. It gives a good list of information.
Aug 26 '10 #2
Nepomuk
3,112 Expert 2GB
Hey there!

OK, let's go through the code.
Expand|Select|Wrap|Line Numbers
  1. ARRAY=("example program" "for test only" "Lets try");
This generates an array with the 3 elements "example program", "for test only" and "Lets try". Pretty easy.
Expand|Select|Wrap|Line Numbers
  1. ELEMENTS=${#ARRAY[@]};
OK, there are a few things in this line. First of all, if you have a variable name, that may not be recognised as one (for example when accessing an array like here), you can put braces around the name. So, if you wanted to access the first element of the array, you would use ${ARRAY[1]}, as just $ARRAY[1] would resolve as example program[1]. (Note: if you access an array without a couter, it will always return the first element.)
Next, the [@] part. The brackets behind the name of an array mean, that you want to access a certain element of that array. Putting an @ symbol there means, that you want to access all of the arrays elements. (Just like $@ means all of the arguments you gave, when calling the script.)
Last but not least, the hash symbol (#). The hash symbol is quite commonly used to express the amount of something - and that is how bash uses it here. So, #ARRAY[@] means "give me the amount of elements in ARRAY[@]" (which as I said before gives you all elements in ARRAY).
Expand|Select|Wrap|Line Numbers
  1. echo $ELEMENTS;
Gives you the number you just got.
Expand|Select|Wrap|Line Numbers
  1. for((i=0;i<$ELEMENTS;i++));do
OK, for this you should know, that there are several forms of the for-loop in bash programming. Traditionally, you would use the form
Expand|Select|Wrap|Line Numbers
  1. for i in `seq $ELEMENTS`
which works with basically all forms of shell (e.g. sh, ksh, csh, ...). If you already know how many times you want to go through the loop, you can also use the form
Expand|Select|Wrap|Line Numbers
  1. for i in {1..3}
, but that didn't work for me when I tested using $ELEMENTS. In this case however, the programmer chose to use the C-like three-expression syntax. This form is easily understandable for anyone with a C-like background, but it's not very common in shell programming. Basically what happens is, that first a variable (i) is initialized, then there's a condition (i<$ELEMENTS) and then it is incremented (i++). The reason, that this whole thing has to be in double brackets is, that if you have single brackets, it's just a sequence of commands. For example,
Expand|Select|Wrap|Line Numbers
  1. (i=0; echo $i)
will just output 0. Now, in pure bash syntax, i<$ELEMENTS doesn't make much sense - to test if the value of i is smaller than $ELEMENTS, you would normally write
Expand|Select|Wrap|Line Numbers
  1. [ $i -lt $ELEMENTS ]
So, when this feature was introduced into bash syntax, they decided to use something they hadn't used before - double brackets.
Oh, and the do starts a block of code, that the for loop should run.
Expand|Select|Wrap|Line Numbers
  1. echo ${ARRAY[$i]} # echo ${ARRAY[${i}]}
The first echo will give you the i'th element of the Array for the reason I told you before. The second one won't do anything, as in this context the hash symbol starts a quote. The reason this quote was added is probably, because previously in the program, accessing variables was normally done with the braces and here he's not using them for the i. So, to show you that it's just a different way of doing the same thing, the programmer added the comment.
Expand|Select|Wrap|Line Numbers
  1. done
This ends the block of code, which was started by do earlier.

OK, hope this helped you. :-)

Greetings,
Nepomuk
Aug 26 '10 #3
johny10151981
1,059 1GB
@ Nepomuk,
thanks for your reply. you have given a great reply.

But still I dont understand why

for loop used nested bracket "((...))" single bracket generates error.
Aug 27 '10 #4
Nepomuk
3,112 Expert 2GB
OK, so in the double brackets it says
Expand|Select|Wrap|Line Numbers
  1. i=0;i<$ELEMENTS;i++
In regular bash syntax, that would be a list of the 3 commands
Expand|Select|Wrap|Line Numbers
  1. i=0
  2. i<$ELEMENTS
  3. i++
The i=0 isn't a problem, that's valid bash code. But if you enter i<$ELEMENTS into a bash shell, you'll get an error because it's invalid code. The correct way to compare those two values would be
Expand|Select|Wrap|Line Numbers
  1. [ $i -lt $ELEMENTS ]
as I wrote in my previous post. The last command, i++ is similar - in standard bash, it doesn't make much sense. There are a few ways to increment a variable with regular bash syntax, e.g.
Expand|Select|Wrap|Line Numbers
  1. i=`expr $i + 1`
or
Expand|Select|Wrap|Line Numbers
  1. i=$[i+1]
or even
Expand|Select|Wrap|Line Numbers
  1. let i++
but just i++ will give you an error message.

So, as simple brackets just mean that you're listing a few commands in bash, listing those commands in single brackets will give you an error. That's why that version doesn't work.

However, since bash 2.04 from what I read, bash also supports the so called "double parentheses construct". This basically allows C-style arithmetics to be used within double brackets (or "parentheses"). You can find more details here, but basically you can use arithmetics within double brackets just like you would use them in any C-style language. The $ symbol before ELEMENTS makes bash replace that variable before running the arithmetics, so you get something like
Expand|Select|Wrap|Line Numbers
  1. i=0;i<3;i++
which in C makes absolute sense. That's why in double brackets, it won't give you an error message.

I hope that cleared up the situation for you. :-)

Greetings,
Nepomuk
Aug 27 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: Magnus Jonneryd | last post by:
Hi, I'm planning on writing a program that interactively is fed input via a shell (bash). I also want to be able to write a shell script that executes various commands related to my program. In...
33
by: apropo | last post by:
what is wrong with this code? someone told me there is a BAD practice with that strlen in the for loop, but i don't get it exactly. Could anyone explain me in plain english,please? char...
1
by: Ennio-Sr | last post by:
Hi all! I'm writing a script that presents the user with a numbered lines menu, each line corresponding to a <case n> which executes a psql command. As the psql-commands are very similar to each...
3
by: sd2004 | last post by:
I am still learning, could someone show/explain to me how to fix the error. I can see it is being wrong but do not know how to fix. could you also recommend a book that I can ref. to ?...
16
by: John Salerno | last post by:
Hi all. I just installed Ubuntu and I'm learning how to use the bash shell. Aside from the normal commands you can use, I was wondering if it's possible to use Python from the terminal instead of...
14
by: dba_222 | last post by:
Dear experts, Again, sorry to bother you again with such a seemingly dumb question, but I'm having some really mysterious results here. ie. Create procedure the_test As
13
by: Studentmadhura05 | last post by:
Hi, I recently started using bash and wrote some code to find certain IPs and related stuff in the leases files by using grep I am trying to switch to perl. I am a bigginer and trying to learn perl...
4
by: melmack3 | last post by:
Hello My PHP script executes many bash/cmd commands. Functions like "exec()" or "system()" cause that new bash/cmd session is started, the command is executed and the session is closed....
6
by: Frantisek Malina | last post by:
What is the best way to do the regular bash commands in native python? - create directory - create file - make a symlink - copy a file to another directory - move a file - set permissions ...
2
by: khoda | last post by:
wasn't sure what forum to put this in, but I'm sure someone here can help me. I have a program that I want to run N times. I'd like to make a bash script that, when run like this: ./script.sh 5...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.