Friday, August 2, 2019

SIMPLE BASH:LOOPING THROUGH A SIMPLE LIST

Here are some simple examples of looping through a list of items in a bash script:

#!/bin/bash

for x in 0 1 2 3 4 5 6 7 8 9
do
        echo $x
done

This is what you get:



You can also cat a file for the list:

This is the same list of numbers stored in a text file:




#!/bin/bash

for x in `cat thisIsAList`
do echo $x
done


You get the same results.  Basically you choose the method that works for the situation.  When looping through a short list of items it is probably more efficient to just put the list in the script while for longer lists it  might be best to use a separate text file.

In the above example the important bit is the "`" characters around the cat command.  This is the lower case character  on the same key with the "~" key(under the ESC key).  This is called command substitution; essentially you use the output of a command to replace the command itself.  
The line above can also be written as "for x in $(cat thisIsAList)"




No comments:

Post a Comment