Prerequisites
- Access to a Unix/Linux-based environment (e.g., Ubuntu, macOS, or a Linux VM) and for Windows you could use WSL (Windows Subsystem for Linux) else git bash.
- A text editor (like Vim, Nano, or VS Code).
- Basic knowledge of using the terminal or command line. (you could refer my blog Shell Scripting: Basic Commands To Just Get You Starting)
Step 1: Create a New Shell Script File
- Open the terminal
- Navigate to the directory you want to save the script
- Use the touch command to create a new file called hello_world.sh
touch hello_world.sh
Step 2: Your First Script
Open the file in your preferred editor(e.g., Vim):
vim hello_world.sh
Your script should start with shebang but if its vim press I to get to insert mode.
#!/bin/bash
The #!/bin/bash line is called a "shebang" and it tells the system to use Bash to run the script in the terminal.
Write a simple echo command to display "Hello, World!" on the terminal:
echo "Hello, World"
Now your script should look like this:
#!/bin/bash
echo "Hello, World"
Now time to save file since its vim at the moment to save it press Esc, type :wq and press Enter.
Step 3: Make the Script Executable
Before you can run your script you need to give executable permission else it wouldn't be recognized as a program to run. Here's the command:
chmod +x hello_world.sh
This command grants execute (+x) permissions to the file.
Step 4: Run Your Script
Run the script just by typing the command
./hello_world.sh
You should see
Hello, World!
Hurry! Congratulations!! you have just written and executed your first shell script.
Step 5: Practice More
Adding on few tasks for your guys who have been following it all till here:
Write a script to display βHello, World!β and current date.
It will help you Understand basics of script writing and command execution.Write a script to print system information like hostname, kernel version and more.
It will help you get comfortable with basic commands and echo statements.Create a script to display the contents of a directory.
It will help you learn file operations and directory commands.
This guide will help you to write and run your first script and help you enhance your understanding with the tasks to practice to get you up and running and stay motivated.
Top comments (0)