BASH 01 - Script Basics

Jarret B

Active Member
Staff member
Joined
May 22, 2017
Messages
235
Reaction score
199
Credits
4,755
This article is the first in a series of articles to cover Bash Scripting. More articles will follow which will build on each other, so make sure you look over each article. It is preferable to read the articles in order (which is why I will number them).

Scripting is a very useful ability for someone using Linux. Making scripts is especially useful for Administrators. Everyone should benefit from Bash Scripting.

Bash is the most common shell interpreter on Linux systems. When you open a Terminal, you are in an interactive shell environment. To verify that your system is using the Bash shell using the command: 'echo "$SHELL"'.

NOTE: Do not copy and paste the command into the Terminal. Inside the shell, the quotes are the quotes that go straight up and down. Most word processors change the regular quotes to curved quotes. The interpreter does not recognize the curved double-quotes or single-quotes.

You should get a response of ‘/bin/bash’ which is the location of the Bash Interpreter. If you get a different response, then your system is using a command interpreter other than Bash.

Script Structure

Scripts consist of three sections: beginning, middle and end.

The beginning of each Bash script is the shebang (#!) followed by the path to the interpreter. Each Bash script you open will start with the line: ‘#!/bin/bash’. The shebang line should always be the first line in the script.

The middle of the script will consist of comments and commands. The interpreter will disregard any comments (#). Once the interpreter comes across the pound (#) character it disregards the rest of the line. Commands are mainly any command that you can type in a Terminal. In later articles, we will go over the other commands you can use to control the flow of the script.

NOTE: The pound (#) must be the first character for the whole line to be a comment. If the comment is placed after a command, there must be at least one space before the pound (#) sign. This is why the last part of the shebang is not a comment.

The ending of a script file is the exit code. Any program or command when it is completed will give a number to signify its exit code. An exit code of '0' notes that the program or command was executed without an error. Numbers other than zero can designate a special number for different types of errors. For simple scripts, an exit code is not needed. Exit codes should be used for good practice. If no exit code is specified the exit code of the last command is used for the whole script.

Commenting on a script is very good practice. Long scripts need comments to allow you to remember details about the script. It could be a long time from the time a script is written before you may need to update it. It could take some time to look it over and everything be clear as to the details. Others may need to look over your scripts or you look at theirs, so it is best to add comments.

Best practices would require something like the following after the shebang and before commands:

Code:
# Author: <your name>
# Date Created: <today’s date>
# Date Modified: <today’s date>
# Description: <description of the script>
# Usage: <list of input and output parameters and info>

When a script is modified, the 'Date Modified' entry should be set to the current date. Any updates should be added to the above. Specific lines can be commented on before the new or modified command line.

Script Security

When the script is first made it cannot be executed until the execution permission is set. To do this, use the following command:

Code:
chmod +x <script_name>

To see the permissions on a script, after the execution permission is allowed, it should be similar to what follows:

Code:
-rwxrwxr-x 1 jarret jarret 67 Nov 7 20:32 test

The main things to look at for the output of the command ‘ls -l test’ are:

The third column shows the owner (jarret) while the fourth column shows the Group owner. The last column shows the filename.

Now, let’s look at the first column of information ‘-rwxrwxr-x’. The information consists of three sets of data. The first four (-rwx) are for the owner. The next three (rwx) are for the Group. The last three (r-x) are for everyone else.

The values are 'r' for Read, 'w' for Write, 'x' for Execute and '-' for None. So, for the Owner of the file, they have Read, Write and Execute. The permissions are the same for the Group named 'jarret'. Everyone else has 'Read' and 'Execute' permissions, which means they can read the script and execute it, but cannot write any changes to it.

The security should be changed to not allow such open permissions. If the script is a personal script only used by you and saved in your Home Folder, then the permissions should be ‘-rwxr--r--’ which, if you are in the same folder as the file, can be set by the command:

Code:
chmod 744 test

If the file is to be saved in a more shared folder, like ‘/usr/local/bin’ for use by everyone, then the permissions should be something like ‘-rwxr-xr-x’. This allows the Owner to make changes, but everyone else can Read and Execute the script, but not make changes to it.

The last bit of security issue is that the file is in a place to allow execution without needing to specify a full path or change to the proper folder. We need to add the script folder into the Path. Place the script in your desired folder and make sure you are not in the same folder. Enter the script's filename on the command line and press Enter. If you get an error that the file is not found, then the folder is not part of the Path.

The Path environment variable is a list of folders that are searched for filenames that are entered. The search starts with the first folder listed and continues to the end of the list. If the file is found, then it is executed. Otherwise, an error is displayed that the file cannot be found.

To see the current path environment variable use the command ‘echo $PATH’. The output should be similar to:

Code:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

If you want all of the users on a system to have access to scripts, place the scripts in the folder ‘/usr/local/bin/’. The specified folder is the second in the PATH variable.

If the scripts are only for you, then place them in a directory in your Home Folder and add the path to the scripts to the Path Environment.

To add to the Path Environment there are two places to do this. The first place is for just your user account. The Path is set in the file '~/.profile'. The second place is to set for all users that log onto the system. If you want the Path set for all users, edit the file '/etc/profile'. The method is the same but can be set in two places. Just be sure that the folder you add is accessible to the user or users for whom you are setting the variable.

NOTE: If it’s for all users, just use the folder ‘/usr/local/bin’ to make things easy. If you want a specific folder of only scripts, then create a new one, such as ‘/usr/local/scripts’ for example. If a new folder is created, be sure to add the Path.

Adding the Path is performed in one of the previously mentioned files. Open the file to edit in your favorite editor. Go to the bottom of the file and on a new line add the following:

Code:
export PATH=”$PATH:/path/to/scripts”

Save and close the file. Just make sure you type the appropriate folder name in place of the ‘/path/to/scripts’.

The changes do not take effect until you reboot or execute the appropriate command. The command to execute is 'source <profile-file>'. The '<profile-file>' should be replaced with the file you just edited. Such as, if you edited the one for all users then run 'source /etc/profile'.

Now, when you run the command ‘echo “$PATH”’ you should see your Path change listed in the output.

Conclusion

This should give you a general start on Bash scripts and their layout. You should also understand the security issues and how to set the Path to make the scripts more available.

Actual scripting techniques will be coming.
 


wizardfromoz

Administrator
Staff member
Gold Supporter
Joined
Apr 30, 2017
Messages
7,120
Reaction score
5,996
Credits
23,583
Nice read, I look forward to the rest of the series.

Jarret you could do a little more with

If the script is a personal script only used by you and saved in your Home Folder,...

... in that, if you mkdir a folder such as

/home/yourusername/bin

or

/home/yourusername/.local/bin

and store your scripts in there, then as soon as you reboot, that folder is automatically added to the start of your $PATH.

So, for example, from the Distro I am currently in

Code:
[email protected]:~$ echo $PATH
/home/chris/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

So in such cases, there is no need to edit profile files.

Cheers

Wizard
 
OP
Jarret B

Jarret B

Active Member
Staff member
Joined
May 22, 2017
Messages
235
Reaction score
199
Credits
4,755
Thanks. I'm going to do some custom scripts and hopefully go over it again.
I thought about a script that makes an empty script file and sets it it to executable, etc.
I learned a long time ago that scripts are extremely handy, but back then they were DOS batch files.
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!

Members online


Top