A shell script is a sequence of commands saved to a file. This file can be executed as a script.
In a shell script, we can use programming features like:
- Conditional statements
- Loops
- Functions
Shell scripts are best suited for automating tasks and can handle complex requirements with ease.
Create a file, for example, demo.sh, and include the following commands:
echo "Welcome to shell script"
date
calUse the following command to grant execute permissions:
$ chmod a+x demo.shYou can run the script in multiple ways:
$ /bin/bash ./demo.sh
$ bash ./demo.sh
$ /bin/bash /home/durgasoft/scripts/demo.sh
$ ./demo.sh # If the default shell is bashNote:
- The default shell is
bash, which executes the script by default. - If you want to use a different shell (e.g., Bourne shell), run the script as follows:
$ /bin/sh ./demo.sh
$ sh ./demo.shThe sha-bang (#!) is used to specify the interpreter responsible for executing a script.
It provides clear instructions about which interpreter to use for the script.
#→ Sharp!→ Bang#!→ Sharp Bang, Sha-Bang, or Shebang
#! /bin/bash→ Specifies that the script should be executed by the Bash shell.#! /bin/sh→ Specifies that the script should be executed by the Bourne Shell.#! /usr/bin/python3→ Specifies that the script should be executed by the Python 3 interpreter.
When a sha-bang is included in the script, you can execute the script directly without explicitly providing the interpreter command.
Q1 Write a Python Script and Execute Without Sha-Bang and With Sha-Bang
Script: test.py
#! /usr/bin/python3
import random
print("Good Morning")
name = input("Enter your name: ")
l = ["sejal", "shrushti", "archana", "arti", "gauri", "preeti"]
print("congratulation ", name)
print("Your best frined is ", random.choice(l))$ python3 ./test.py
$ python3 /home/durgasoft/scripts/test.py$ ./test.py
$ /home/durgasoft/scripts/test.pyQ2 Consider the Following Script:
Script: demo.sh
#! /bin/rm
echo "It is a beautiful script"$ ./demo.sh- This is equivalent to running:
$ rm ./demo.sh
- The
demo.shfile will be removed as the script is executed by thermcommand.
Write and Run a Shell Script That Prints the Current System Date and Time
Script: date.sh
#! /bin/bash
echo "The current System Date and Time:"
date-
Provide execute permissions:
$ chmod a+x date.sh
-
Run the script:
$ ./date.sh
Output:
The current System Date and Time: Wed Dec 4 21:01:49 IST 2019