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.shStep 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.shMethod B: Direct Execution (Recommended)
This is the professional way to run scripts. It involves two sub-steps:
- Grant Permissions: Make the file executable.
chmod +x myscript.sh - 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."
fiSummary Workflow
| Step | Command | Purpose |
|---|---|---|
| Create | nano script.sh | Open editor for writing. |
| Protect | chmod +x script.sh | Make the script executable. |
| Execute | ./script.sh | Run the finished tool. |
[!TIP] Extension doesn't matter (technically) While
.shis the convention, Linux identifies scripts by the Shebang line and Execute Bit, not the file extension. However, using.shis a best practice for clarity.