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


-rw-r--r--. 1 root root 32 Feb 17 20:32 hello.sh



Download 1.85 Mb.
View original pdf
Page27/67
Date26.02.2024
Size1.85 Mb.
#63678
1   ...   23   24   25   26   27   28   29   30   ...   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
-rw-r--r--. 1 root root 32 Feb 17 20:32 hello.sh
[root@rhel-instance
]# chmod +x hello.sh

[root@rhel-instance
]# ls -l hello.sh

-rwxr-xr-x. 1 root root 32 Feb 17 20:32 hello.sh
And we run it as follows:
[root@rhel-instance
]# ./hello.sh

hello world!
We have created our first shell script. Congratulations!
Tip
The commands must be in the path to run in any working directory, as stated by the PATH variable. If our command (or shell script) is not in one of the directories specified in the path, we will specify the running directory, in this case, using the . shortcut for the current directory and the / separator.
Let’s use some variables. We can define a variable by simply providing its name and the value we want. Let’s try replacing world with a variable. To use it, we prepend the $ symbol to the name of the variable and it will be used. The script will look as follows:
#!/bin/bash
PLACE=''world''
echo 'hello $PLACE!''

Basic Commands and Simple Shell Scripts
94
We can run the script, obtaining the same output as before:
[root@rhel-instance
]# ./hello.sh

hello world!
To have more clarity, when using the value of the variable, we will put the name of it between curly braces, { and }’, and take this as a good practice.
The previous script will look as follows:
#!/bin/bash
PLACE=''world''
echo 'hello ${PLACE}!''
We now know how to create a basic script, but we may want to have greater control over it by using some programmatic capabilities, starting with loops. Let’s go for it!
for loops
What if we want to run the same command over a list of places That’s what a for loop is used for. It can help iterate over a set of elements, such as a list or a counter, for example.
The for loop syntax is as follows for To specify the iteration do To specify the action done To close the loop
We can define a space-separated list to try it and iterate through it with our first for loop:
#!/bin/bash
PLACES_LIST="Madrid Boston Singapore World"
for PLACE in ${PLACES_LIST}; do echo "hello ${PLACE}!"
done
Let’s run it. The output will look as follows:

Download 1.85 Mb.

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




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

    Main page