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
Page29/67
Date26.02.2024
Size1.85 Mb.
#63678
1   ...   25   26   27   28   29   30   31   32   ...   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

¡Hola Madrid!
We have a problem it only says hello to Madrid. What happens if we want to run the previous code on the ones not matching the condition That’s when we extend the conditional using else for the items that do not match.
And now, we have an example of a conditional using else:
#!/bin/bash
PLACES_LIST="Madrid Boston Singapore World"
for PLACE in ${PLACES_LIST}; do if [ PLACE = "Madrid" ]; then echo ''¡Hola ${PLACE}!''
else echo 'hello ${PLACE}!''
fi done
We can run it:
[root@rhel-instance
]# ./hello.sh

¡Hola Madrid!

Using system documentation resources
97
hello Boston!
hello Singapore!
hello World!
As you see, it’s simple to use the conditionals in a script and provide a lot of control over the conditions under which a command is run. We now need to control when something may not be running correctly.
That’s what the exit codes (or error codes) are for. Let’s go for it!
Exit codes
When a program is run, it provides an exit code, specifying whether it ran OK or whether there was an issue. That exit code is stored in a special variable called Lets take a look at it by running ls hello.sh:
[root@rhel-instance
]# ls hello.sh

hello.sh
[root@rhel-instance
]# echo $?

0
When the program runs OK, the exit code is zero, What happens when we try to list a file that doesn’t exist (or run any other command incorrectly, or that is having issues Let’s try listing a nonexistent file:
[root@rhel-instance
]# ls nonexistentfile.txt

ls: cannot access 'nonexistentfile.txt': No such file orb
]# echo $?

2
You seethe exit code is not zero. We will go to the documentation and check the number associated with it to understand the nature of the issue.
When running a command in a script, check for the exit code and act accordingly. Let’s now review whereto find further information on the commands, such as exit codes or other options, in the following section.

Download 1.85 Mb.

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




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

    Main page