Enter your email address:

Delivered by FeedBurner

for - Control flow statement in shell scripts


StumbleUpon Toolbar

One real important part of programming is to control the flow of the program, you need to be able to repeat some part of the code, jump to another part, etc, depending on the estate of some variables, there are a lot of commands to achieve that, and one of them is for

It can be used directly at the command line like this example using basename

for i in *.jpg; do echo $i $(basename $i .jpg); done

This command will print all the filenames which ends with .jpg with and without the .jpg suffix.

This line has three parts, divided by the semicolon.

The first part for i in *.jpg assigns the names of the files ending in .jpg to the variable i (one at a time, not like a matrix), then the second part do echo $i $(basename $i .jpg) prints to the screen the value of the variable i, and then the variable i without the trailing .jpg, so you may have an output like this.

100_0055.jpg 100_0055
100_0056.jpg 100_0056
100_0057.jpg 100_0057
100_0058.jpg 100_0058
100_0059.jpg 100_0059
100_0060.jpg 100_0060
100_0061.jpg 100_0061
100_0062.jpg 100_0062
100_0063.jpg 100_0063
100_0064.jpg 100_0064
100_0065.jpg 100_0065
100_0066.jpg 100_0066
100_0067.jpg 100_0067
100_0068.jpg 100_0068
100_0069.jpg 100_0069

Which is the filename itself $i and the file name without the trailing .jpg $(basename $i .jpg).

Finally the last part done ends the sequence when there is no more file with .jpg at the end of its name, in the working directory.

As you can see this is really useful to work with lots of files in batches

Trackback URL for this post:

http://www.go2linux.org/trackback/454
StumbleUpon Toolbar

 If you like this article, subscribe to our full rss

If this article was somehow useful for you, you can leave something in the tip's jar

Please post your question in our forum and use comments only to leave your comments about the article, thanks.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

Captcha
This question is for testing whether you are a human visitor and to prevent automated spam submissions.

This site is proudly hosted at Bluefur Hosting