A shell script is a file that contains ASCII text. When writing a shell script, you use a text editor. Open your text editor and type in your first script as follows:
# My first script
echo “Hello World!”
The first line of the script is important.it is a special clue given to the shell indicating what program is used to interpret the script. In this case, it is /bin/bash.
The second line is a comment. Everything that appears after a “#” symbol is ignored by bash. As your scripts become bigger and more complicated, comments become vital. They are used by programmers to explain what is going on so that others can figure it out.
The last line is the echo command. This command simply prints what it is given on the display.
We have to give the shell permission to execute your script. This is done with the chmod command as follows:
[[email protected] me]$ chmod 755 my_script
The “755” will give you read, write, and execute permission. Everybody else will get only read and execute permission. If you want your script to be private (i.e., only you can read and execute), use “700” instead.
At this point, your script will run. Try this:
[[email protected] me]$ ./my_script
You should see “Hello World!” displayed. If you do not, see what directory you really saved your script in, go there and try again.
This list of directories is called your path. You can view the list of directories with the following command:
[[email protected] me]$ echo $PATH
This will return a colon separated list of directories that will be searched if a specific path name is not given when a command is attempted. In our first attempt to execute your new script, we specified a pathname (“./”) to the file.
You can add directories to your path with the following command, where directory is the name of the directory you want to add:
[[email protected] me]$ export PATH=$PATH:directory
A better way would be to edit your .bash_profile file to include the above command. That way, it would be done automatically every time you log in.
Most modern Linux distributions encourage a practice in which each user has a specific directory for the programs he/she personally uses. This directory is called bin and is a subdirectory of your home directory. If you do not already have one, create it with the following command:
[[email protected] me]$ mkdir bin
Move your script into your new bin directory and you’re all set. Now you just have to type:
[[email protected] me]$ my_script
And your script will run.
Kipkorir is the founder of advancelearnlinux.com with over 6 years in information technology(Microservices, Analytics, Power BI, and Database Development). He's also passionate about Data analytics and Data Science.