DevOps
Shell Scripting
Running Scripts

Running Shell Scripts

This guide walkthrough the process of creating, configuring, and executing your first shell script on a Linux environment.

Step 1: Create the Script File

Use a command-line editor like nano or vim to create a new file with the .sh extension.

# Create and open a new script
nano myscript.sh

Step 2: Add Script Logic

Every script should start with a Shebang. This tells the system which interpreter to use.

#!/bin/bash
 
# A simple message
echo "Hello, world!"
echo "This is my first shell script."

Step 3: Run the Script

There are two primary ways to execute your script.

Method A: Using the Interpreter

You can pass the script as an argument to the bash command. This works regardless of the file's permissions.

bash myscript.sh

Method B: Direct Execution (Recommended)

This is the professional way to run scripts. It involves two sub-steps:

  1. Grant Permissions: Make the file executable.
    chmod +x myscript.sh
  2. Run Directly: Use the ./ prefix.
    ./myscript.sh

4. Practical Example: Interactive Script

Let's create a script that interacts with the user using variables and conditionals.

#!/bin/bash
 
echo "--- User Management System ---"
read -p "Enter your name: " USER_NAME
read -p "Are you an admin? (yes/no): " IS_ADMIN
 
if [[ "$IS_ADMIN" == "yes" ]]; then
    echo "Welcome, Admin $USER_NAME. Access granted."
else
    echo "Hello $USER_NAME. You have standard user access."
fi

Summary Workflow

StepCommandPurpose
Createnano script.shOpen editor for writing.
Protectchmod +x script.shMake the script executable.
Execute./script.shRun the finished tool.

[!TIP] Extension doesn't matter (technically) While .sh is the convention, Linux identifies scripts by the Shebang line and Execute Bit, not the file extension. However, using .sh is a best practice for clarity.