Writing your first Linux shell script enables you to automate tasks and streamline your workflow. This tutorial guides you through creating a simple bash script, from choosing an editor to adding logic and control structures. By the end, you'll have written and executed your first working shell script.

How to Write Your First Shell Script

  1. Step 1: Choose a Text Editor

    Select a text editor to write your script. Popular options include Vim, Emacs, Nano, or graphical editors like Sublime Text or VSCode.

  2. Step 2: Start with a Shebang

    At the beginning of your script, include a shebang line to specify the interpreter. For bash scripts, use:

    #!/bin/bash

    This tells the system to interpret the script using the bash shell.

  3. Step 3: Write Your Script

    Add commands and logic to achieve your desired functionality. Here's a simple example that prints "Hello, World!" to the terminal:

    #!/bin/bash
    
    echo "Hello, World!"
  4. Step 4: Save Your Script

    Save your script with a .sh extension to indicate that it is a shell script. For example, name it hello_world.sh.

  5. Step 5: Make Your Script Executable

    Before you can run your script, make it executable using the chmod command:

    chmod +x hello_world.sh
  6. Step 6: Run Your Script

    Execute your script from the command line:

    ./hello_world.sh

    If everything is set up correctly, you should see "Hello, World!" printed to the terminal.

  7. Step 7: Add Comments

    Comments are essential for documenting your code and making it more understandable. Add comments to your script using the # symbol:

    #!/bin/bash
    
    # This is a simple script that prints "Hello, World!"
    
    echo "Hello, World!"
  8. Step 8: Use Variables and Arguments

    You can use variables to store data and arguments passed to your script. Here's an example that takes a name as an argument and prints a personalized greeting:

    #!/bin/bash
    
    # This script takes a name as an argument and prints a greeting
    
    NAME=$1
    echo "Hello, $NAME!"

    Run the script with a name argument:

    ./hello.sh John

    This would print "Hello, John!".

  9. Step 9: Add Control Structures

    Use control structures like if, else, elif, for, and while to add conditional logic and looping to your scripts. Here's a simple example using an if statement to check if a file exists:

    #!/bin/bash
    
    # Check if a file exists
    
    FILE="example.txt"
    
    if [ -f "$FILE" ]; then
        echo "$FILE exists."
    else
        echo "$FILE does not exist."
    fi

    This script checks if a file named example.txt exists in the current directory and prints a corresponding message.

  10. Step 10: Learn and Experiment

    Shell scripting is a vast topic, and there's always more to learn. Experiment with different commands, techniques, and scripts to improve your skills and understanding.