Create Your First Script
Shell scripting is one of the most efficient ways to automate tasks on Unix-based systems. In this tutorial, we’ll guide you through creating your first shell script, understanding basic commands, and executing them step-by-step. Let’s get started!
What is Shell Scripting?
A shell script is a plain text file containing a series of commands that the shell executes sequentially. It helps automate complex or repetitive tasks.
Key Features
- Automates repetitive tasks.
- Executes multiple commands with a single script.
- Acts as a form of documentation for workflows.
- Supports decision-making with if-else statements, loops, and variables.
Your First Shell Script
Let’s create a simple script to understand how shell scripting works.
Step 1: Create the Script
- Open your terminal and create a new file named
first.sh
. - Add the following lines to the file:
echo "Hello World" echo "This is our first shell script." pwd date
Step 2: Change File Permissions
By default, the script doesn’t have execute permissions. Use the chmod
command to grant execute permissions:
chmod +x first.sh
Step 3: Run the Script
Execute the script using the ./
command:
./first.sh
Expected Output
Hello World
This is our first shell script.
/home/kali/shellscript-youtube
Wed May 4 06:36:07 AM EDT 2022
Explaining the Commands
-
echo
:- Prints the text to the terminal.
- Example:
echo "Hello World"
.
-
pwd
:- Displays the current working directory.
-
date
:- Prints the current date and time.
-
chmod +x
:- Grants execute permissions to the script.
-
./first.sh
:- Executes the shell script.
Tips
-
Add Comments:
- Use
#
to include notes and explanations in your script for better understanding and maintenance.
- Use
-
Test Small Blocks of Code:
- Test individual commands before adding them to the script.
-
Use Meaningful Names:
- Give your script files clear and descriptive names.
Conclusion
Congratulations! You’ve successfully created and executed your first shell script. Shell scripting is an effective way to automate tasks and save time. This is just the beginning of your scripting journey.
For more tutorials and resources, visit learning-ocean.com. In the next blog post, we’ll discuss Shebang in detail. Until then, Happy Scripting!