Introduction
You will be developing and maintaining a series systemScripts, you need to start here.
1. Script creation
- You first need to create a script that you can develop:
- You have created a series of directories using
mkdir -p ... - changed current path to the newely created directories
cd ... - finally you create a file with
touchin the../bash/directory.
2. Basics
Bash is an interpreter and will execute each line one at a time, so in order to do that we need to specify that the script we are writing is designed for that.
-
Open the newly created file with the
vimtext editor -
Reproduce the following:
-
Run the script:
-
Lets change the file modifiers so that the
systemStat.shis now an executable.$ ls -lah > drwxr-xr-x dev users 4.0 KB Tue Oct 10 19:13:49 2023 . > drwx------ dev users 4.0 KB Tue Oct 10 12:40:13 2023 .. > .rw-r--r-- dev users 0 B Tue Oct 10 19:13:49 2023 systemStats.sh -
Running the following to change permissions for this:
-
Now that the file is an exectuable we can call it like this:
-
As proof lets use
catdirectly: -
Changing the shebang to
bashwill ensure thebashprogram is called instead. -
Again remember to press
ito enter INSERT mode, and reproduce the following -
Run the program and you will get the same output as
bash systemStats.sh
3. A more meaningful script
-
Scripting is useful for automating process and system admin. For example, getting lots of information from all over the OS using one script.
-
Lets add that to our script:
-
Reproduce the following:
-
Running this will look like:
-
Running
cat /etc/os-releasewill give you the following: -
What we need to isolate is the OS's name, which is identifiable via the
NAME=.... To do this will use two exta packages,grepandawkto get what we need. -
Next we pipe the result of that search,
NAME="Debian GNU/Linux"intoawkto grab onlyDebian GNU/Linuxwhere we split the result based on a delimeter,=, with the option-F(Field delimeter). The delimited format is: -
However we want the string between the
", so we modify the command to take more than one delimitter, order matters: -
Now that we have isolated
Debian GNU/Linux, we can add this functionality to our script, after the linecat /etc/hostname: -
If you run this program now you should get the following output:
-
Now we want the OS version from the
VERSION="11 (bullseye)"output ofcat /etc/os-release, using what you have learned above try to isolatebullseye.Explanation
-
The first field,
$1, is everything before the equal sign (=), which is VERSION. -
The second field,
$2, is everything between the equal sign (=) and the double quote ("), which is11. -
The third field,
$3, is everything between the double quote (") and the opening parenthesis ((), which is a space character. -
The fourth field,
$4, is everything between the opening parenthesis (() and the closing parenthesis ()), which isbullseye.
-
-
Once completed add the code to the script like before, run to verify the expected output: