Running through this first lesson in creating bash scripts we will begin by looking at the BASH script fundamentals. These include the following objectives:
- Where do I create my scripts?
- How do I name scripts?
- How can I execute and debug scripts as required?
Understanding the PATH Environment
When running executables in Linux only those directories that are included in your PATH variable are searched. The current directory is not part of the search unless it too is listed in the PATH. To read the contents of a variable we use the echo command.
When you are developing and testing scripts creating them in the bin subdirectory located in your home directory is a great idea as this is often included in your PATH statement. Linux will only look for scripts within the PATH statement and not in the current directory. Adding the scripts to your own bin directory, ~/bin, means that you can execute the script from any directory without having to use the full path to the script. An alternative is to supply the path to the script, if it is the current directory the relative path with be: ./scriptname.
Adding a .sh extension helps in the uniqueness of the script name and identifies the file type easily to yourself. Linux itself does not need the .sh extension but makes sense for us to add it.
The reality is the Linux filenames are just filenames and do not contain and extension. If a dot is included in the filename it makes up part of the name and does not separate the file name from the file extension.
Adding the Execute Permission
Newly created scripts will not be executable by default. We can use the “change mode” or chmod program to add in the execute permission:
- chmod +x <scriptname> #adds execute to all users
- chmod u+x <scriptname> #just adds the execute permission to the user owner
If you do not require the script to be independently executed then it is also possible to use BASH to open and run the script:
Of course, if you type as badly as I do then your script may not work first off. To help with this you may need to debug the script. One way is to use BASH to run the script again, this time using the -x option. Running the command bash -x <scriptname> you will be shown the debug information produced as the script executes. This is especially useful to see how conditional statements were evaluated within the script.