# Your First Ubuntu Bash Script: From "Access Denied" to Automation

Now that you understand how permissions and the terminal work, it’s time to combine those skills. A **Bash Script** is simply a plain text file containing a series of commands. Instead of typing them one by one, you run the script, and Ubuntu executes them all in order.

---

## 1. The Anatomy of a Script

Every Bash script starts with a special line called a **Shebang**. It tells Ubuntu which "interpreter" to use to read the file.

```bash
#!/bin/bash

```

* **#!**: The Shebang.
* **/bin/bash**: The location of the Bash program.

---

## 2. Creating Your First Script

Let’s create a simple script that backs up a file and tells us the current system status.

### Step 1: Create the file

Open your terminal and type:
`nano myscript.sh`

### Step 2: Write the code

Type the following into the Nano editor:

```bash
#!/bin/bash

# This is a comment - Ubuntu ignores lines starting with #
echo "Starting the magic script..."

# Create a directory for backups
mkdir -p ~/my_backups

# Copy a file (replace 'test.txt' with a real file name)
cp test.txt ~/my_backups/test_backup.txt

echo "Backup complete!"
echo "Your uptime is:"
uptime

```

### Step 3: Save and Exit

Press **Ctrl + O** (to write out), then **Enter**, then **Ctrl + X** (to exit).

---

## 3. The "Permission" Bridge

If you try to run your script now by typing `./myscript.sh`, you will get that famous **"Permission Denied"** error. This is because new files aren't allowed to "run" as programs by default.

**Give it the green light:**
`chmod +x myscript.sh`

Now, you can run it:
`./myscript.sh`

---

## 4. Using Variables and Input

To make scripts useful, you need them to be dynamic. You can store data in **Variables**.

**Example of a dynamic script:**

```bash
#!/bin/bash

NAME="Ubuntu User"
echo "Hello $NAME, what folder should I create?"

# Read user input
read FOLDER_NAME

mkdir $FOLDER_NAME
echo "Folder '$FOLDER_NAME' has been created."

```

---

## 5. Logic: If/Then Statements

Scripts can make decisions. This is the heart of automation.

```bash
#!/bin/bash

FILE="important_data.txt"

if [ -f "$FILE" ]; then
    echo "$FILE exists. Proceeding with update..."
else
    echo "Error: $FILE not found. Stopping script."
    exit 1
fi

```

---

## 6. Why Bother with Scripting?

In 2026, automation is the standard. You can use Bash scripts to:

* **Auto-update** your system every Monday at 2 AM.
* **Batch rename** thousands of photos in a split second.
* **Set up a new server** by installing all your favorite apps with one command.

---

### Pro Tip: The PATH

If you want to run your script from *anywhere* without typing the full path, move it to `/usr/local/bin` using:
`sudo mv myscript.sh /usr/local/bin/myscript`

Now, you can just type `myscript` in any terminal window!