Creating basic shell scripts95
hello Singapore!hello World!Using the for loop can be very interesting when
reading the list from an external command. We can do so by putting the external command between $( and ).
TipBackticks, ', can also be used to run a command and get its output as a list, but we will stick to the previous expression for clarity.
One example of a usable external command can be ls. Let’s create the txtfiles.sh script with the following content:
#!/bin/bash for TXTFILE in ls *.txt); do echo ''TXT file ${TXTFILE} found ''
done
Make it executable and run it:
[root@rhel-instance
]# chmod +x txtfiles.sh[root@rhel-instance
]# ./txtfiles.shTXT file error.txt found!TXT file non-listing.txt found!TXT file usr-files.txt found!TXT file var-files.txt found!You see how we can now
iterate over a set of files, including, for example,
changing their names, finding and replacing content in them, or simply making a specific backup of a selection of files.
We’ve seen several ways in which to iterate
a list with the for loop, which can be very useful when it comes to automating tasks. Now, let’s move onto another programmatic capability in scripts – conditionals.
if conditionalsSometimes, we may want to execute something different for
one of the elements in a list, or only if ab conditionbis happening. We can use the if conditional for this.
The if conditional syntax is if to specify the condition.
Basic Commands and Simple Shell Scripts
96
Conditions are usually specified between brackets ([ and ]):
• then To specify the action fi: To close the loop else This is used as a then element when the condition is not matched.
Let’s change our previous hello.sh script to say "hello to Madrid"
in Spanish, as follows:
#!/bin/bash
PLACES_LIST="Madrid Boston Singapore World"
for PLACE in ${PLACES_LIST}; do if [ PLACE = "Madrid" ]; then echo ''¡Hola ${PLACE}!''
fi done
Then, run it:
Share with your friends: