3 Basic Commands and Simple Shell Scripts Once you have your first Red Hat Enterprise Linux rhel


[root@rhel-instance ]# ./hello.sh



Download 1.85 Mb.
View original pdf
Page28/67
Date26.02.2024
Size1.85 Mb.
#63678
1   ...   24   25   26   27   28   29   30   31   ...   67
Pablo Iranzo Gómez, Pedro Ibáñez Requena, Miguel Pérez Colino, Scott McCarty - Red Hat Enterprise Linux 9 Administration-Packt Publishing (2022) -chap 3 82 - 180
[root@rhel-instance
]# ./hello.sh

hello Madrid!
hello Boston!

Creating basic shell scripts
95
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 ).
Tip
Backticks, ', 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.sh

TXT 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 conditionals
Sometimes, 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:

Download 1.85 Mb.

Share with your friends:
1   ...   24   25   26   27   28   29   30   31   ...   67




The database is protected by copyright ©ininet.org 2024
send message

    Main page