Shell Script · First Basic Script

Shell Scripting · Lesson 4

First Basic Script

Create your first shell script step by step. Set executable permission using chmod. Run script in different ways. Common beginner mistakes and solutions.

What Is a Shell Script?

A shell script is a text file containing a sequence of Linux commands. These commands are executed line by line by the shell.

Scripts help automate tasks, reduce manual work, and ensure consistency across systems.

Why Execution Permission Matters

Linux treats scripts like normal files. To execute a script directly, it must have execute permission.

Without execute permission, the system will block execution for security reasons.

Script File

A plain text file containing shell commands.

Execution Permission

Required to run a script directly using ./script.sh.

Execution Methods

Run using ./script.sh, bash script.sh, or sh script.sh.

Step-by-Step: Create & Run Script

1. Create Your First Script File

Create a new file using a text editor. Here we use nano.

terminal — bash
first-script
nano hello.sh

2. Write Your First Script

Add a shebang and a simple echo command.

terminal — bash
first-script
#!/bin/bash
echo "Hello World from my first script"

3. Check File Permissions

By default, a new file does not have execute permission.

terminal — bash
first-script
ls -l hello.sh
-rw-r--r-- 1 user user 45 hello.sh

4. Give Execute Permission

Make the script executable using chmod.

terminal — bash
first-script
chmod u+x hello.sh
 
ls -l hello.sh
-rwxr--r-- 1 user user 45 hello.sh

5. Execute the Script

Run the script using ./ when it has execute permission.

terminal — bash
first-script
./hello.sh

6. Run Script Using Shell Command

You can also execute a script without execute permission.

terminal — bash
first-script
bash hello.sh
sh hello.sh

Common Mistakes Beginners Make

Avoid These Issues

  • Forgetting to add execute permission.
  • Typing ./script.sh without execute permission.
  • Using Windows line endings (CRLF).
  • Missing or incorrect shebang line.

Practice Task – Your First Script

  • Create a script named hello.sh.
  • Add a shebang and print your name.
  • Give execute permission.
  • Run it using ./hello.sh.
  • Try running with bash hello.sh.

Next lesson: Variables in Shell Scripting