DEV Community

Basanta Bhusan Khadka
Basanta Bhusan Khadka

Posted on

Shell Scripting: Writing and Running Your First Script

Prerequisites

  1. 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.
  2. A text editor (like Vim, Nano, or VS Code).
  3. 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

  1. Open the terminal
  2. Navigate to the directory you want to save the script
  3. Use the touch command to create a new file called hello_world.sh
touch hello_world.sh
Enter fullscreen mode Exit fullscreen mode

Step 2: Your First Script
Open the file in your preferred editor(e.g., Vim):

vim hello_world.sh
Enter fullscreen mode Exit fullscreen mode

Your script should start with shebang but if its vim press I to get to insert mode.

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Now your script should look like this:

#!/bin/bash
echo "Hello, World"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

You should see

Hello, World!
Enter fullscreen mode Exit fullscreen mode

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:

  1. Write a script to display β€œHello, World!” and current date.
    It will help you Understand basics of script writing and command execution.

  2. 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.

  3. 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)