Open Source Projects
This is an introduction to Shell Programming tutorial.
These are the commands that we execute by typing in the shell prompt.
Example: The cal command will print the calendar and will show us the current month.
In simple terms a Shell Program is a series of Unix commands written to perform some task.
Shell Program is also referred as Shell Script.
Open the terminal and using the vi or vim command create a file and give it any name of your choice and save it with the extension .sh.
Example: In the following example we are creating a helloworld.sh file using the vi command.
YUSUF-MBP:example yusufshakeel$ ls -la
drwxr-xr-x 3 yusufshakeel staff 96 Dec 29 09:10 .
drwxr-xr-x@ 5 yusufshakeel staff 160 Dec 29 09:10 ..
-rw-r--r-- 1 yusufshakeel staff 19 Dec 29 09:09 helloworld.sh
The first line of a shell script file is called the Shebang line and it contains the absolute path of the Bash interpreter.
The shebang line given above instructs the program loader to run the interpreter /bin/sh and pass the content of the shell script file as the first argument.
Some of the commonly seen Shebang lines that we will encounter are given below.
Lets start our journey by printing "Hello World" using a Shell Script.
Open the helloworld.sh file using the vi command.
Once the file opens press the i key to enter into INSERT mode to start typing some code.
Now write the following code inside the file.
echo "Hello World"
In the above code we are using the echo command to print the string "Hello World".
Now press the Esc key to come out of the INSERT mode. Then type :wq keys to save the file and exit.
Awesome! We have successfully created our first shell script file. Now lets go ahead and execute the script.
To execute a shell script file we type the sh filename command in the terminal.
So, to execute the helloworld.sh script file we will type the following command in the terminal.
YUSUF-MBP:example yusufshakeel$ sh helloworld.sh
If you are unable to execute the shell script then you can make it executable using the chmod command.
In the following example we are making the helloworld.sh file executable.
$ chmod +x helloworld.sh
We use shell script when we want to automate our tasks. For example, we can create a shell script and setup a cron job to remove temporary files from the server that are older than 7 days.
Have fun learning :-)
Copyright © 2014 - 2018 DYclassroom. All rights reserved.
rendered in 0.0299 sec