VMware ESXi and vSphere Cluster Management
Write Simple Shell Scripts in Linux
Learn how to create, edit, make executable, and run Linux shell scripts using commands, variables, user input, and simple if statements.
A shell script is a text file containing shell commands that are executed as a program. Instead of typing the same commands interactively in a terminal, you can place them in a file and run them in sequence.
Bash is a widely used Linux command interpreter and scripting shell. The examples in this lesson target Bash or a compatible POSIX-style shell. Shell features can differ, so a script written specifically for Bash may not behave the same way when run with another shell.
The .sh filename extension is a useful convention for identifying shell scripts, but it is not technically required. A file named backup can be a shell script just as easily as backup.sh.
Create a Basic Script File
Choose a working directory, then open a new file with a text editor. For example, the following command opens a file named hello.sh in the Nano editor:
nano hello.sh
Put an interpreter directive, called a shebang, on the first line:
#!/bin/bash
A shebang begins with #! and identifies the interpreter used when the file is executed directly. Here, it tells Linux to use Bash. Add a meaningful filename so that the script's purpose is easy to recognize.
Run a Single Command from a Script
After the shebang, add an echo command. echo prints text or variable values to the terminal.
#!/bin/bash
echo "Hello from a shell script!"
Each line can contain a shell command. Save the file and exit the editor. At this point, the file contains a script, but it may not yet have permission to run as a program.
Make the File Executable
Linux uses permission modes to control whether a file can be read, modified, or executed. Use chmod to change a file's permission mode. The +x option adds executable permission:
chmod +x hello.sh
You can inspect the result with ls -l:
ls -l hello.sh
In the output, executable permission is shown by an x in the permission string, such as -rwxr-xr-x. The exact permissions may differ according to your system and umask.
Execute the Script
Run an executable script in the current directory with:
./hello.sh
The ./ prefix means “the current directory.” The current directory is the directory where your terminal is currently working. Linux usually does not search the current directory when looking for commands in PATH, an environment variable containing directories searched for executable commands. Therefore, entering only hello.sh may produce a “command not found” error.
The expected output is:
Hello from a shell script!
You can also run the file through Bash:
bash hello.sh
This alternative does not require the file to have executable permission because the bash command is being executed, and it reads hello.sh as input.
Put Multiple Commands in One Script
Commands normally run from top to bottom. This example prints a label and then runs date, a command that displays the current system date and time:
#!/bin/bash
echo "The current date and time is:"
date
After saving and making the script executable, run it with ./show-date.sh. The output will resemble this, although the date and time will depend on your system:
The current date and time is:
Wed Aug 19 14:30:00 UTC 2026
A blank line in a script improves readability. It does not execute a command.
Define and Use Shell Variables
A variable is a named value stored for reuse in a script. Assign a value with the variable name, an equals sign, and the value. Do not put spaces around the equals sign:
name="Ada"
To read the value, use variable expansion: write $name or ${name}. Expansion means that the shell replaces the reference with the value stored in the variable.
#!/bin/bash
name="Ada"
echo "Hello, $name!"
The output is:
Hello, Ada!
Braces make the variable boundary explicit when text immediately follows the variable name:
name="Ada"
echo "${name}Smith"
Use quotes around values that contain spaces, and generally quote variable expansions when they represent text:
full_name="Ada Lovelace"
echo "Welcome, $full_name"
Without quotes during assignment, the shell can interpret spaces as separators. Quoting also prevents many unexpected word-splitting problems when a variable is expanded.
Read User Input
The read shell builtin accepts input from the user and stores it in a variable. Use read -r as the safer general form because it treats backslashes as literal input rather than interpreting them as escape characters.
#!/bin/bash
printf "What is your name? "
read -r name
echo "Hello, $name!"
The script displays a prompt, waits for the user to type a response and press Enter, then prints the captured value. A sample session looks like this:
What is your name? Ada
Hello, Ada!
Here, name is assigned after the user enters text. Quoting "$name" preserves spaces in the response when it is printed or used in another command.
Use Simple if Statements
A conditional runs commands only when a test is true or false. An if statement uses the keywords if, then, else, and fi. The word fi ends the statement.
if condition; then
commands_when_true
else
commands_when_false
fi
Shell test syntax requires spaces around the brackets when brackets are used. Always quote variable expansions in string tests so an empty value or a value containing spaces does not break the expression.
This script handles an empty name differently from a supplied name:
#!/bin/bash
printf "Enter your name: "
read -r name
if [ -z "$name" ]; then
echo "Please provide a name."
else
echo "Hello, $name!"
fi
The -z test is true when the quoted string has zero characters. If the user enters nothing, the first branch runs. Otherwise, the else branch prints a personalized greeting.
You can also compare a variable with an expected string:
answer="yes"
if [ "$answer" = "yes" ]; then
echo "Continuing."
else
echo "Stopping."
fi
Use = for a basic string comparison. Keep the spaces around the test operator and quote both sides.
Complete Examples
Minimal Greeting Script
#!/bin/bash
echo "Hello from Linux!"
Save this as hello.sh, run chmod +x hello.sh, and execute it with ./hello.sh. The terminal prints a short greeting.
Date Display Script
#!/bin/bash
echo "The current date and time is:"
date
The label is printed first, followed by the output of date, demonstrating top-to-bottom execution.
Stored-Name Greeting
#!/bin/bash
name="Grace"
echo "Hello, ${name}!"
This script assigns a name and reuses it through variable expansion.
Interactive Name Prompt
#!/bin/bash
printf "Enter your name: "
read -r name
echo "Hello, $name!"
The script waits for input and then includes the entered value in its output.
Conditional Greeting
#!/bin/bash
printf "Enter your name: "
read -r name
if [ -z "$name" ]; then
echo "No name was entered."
else
echo "Hello, $name!"
fi
This example connects input handling with conditional logic. It produces a different result when the input is empty.
Basic Shell Script Commands and Syntax
| Item | Purpose | Example usage | Notes |
|---|---|---|---|
echo | Print text or variable values | echo "Hello" | Quote text and expansions when appropriate. |
date | Display the current system date and time | date | Output format depends on options and the system. |
chmod +x | Add executable permission | chmod +x hello.sh | Required for direct execution with ./. |
./script-name | Run a script in the current directory | ./hello.sh | The ./ prefix identifies the file path. |
| Variable assignment | Store a value | name="Ada" | No spaces are allowed around =. |
$variable expansion | Insert a stored value | echo "$name" | ${name} is useful when boundaries need to be clear. |
read -r variable | Store interactive input | read -r name | -r preserves backslashes as literal input. |
if ... then ... else ... fi | Choose commands based on a test | if [ -z "$name" ]; then ... fi | Use spaces in test syntax and close the block with fi. |
Ways to Run a Shell Script
| Method | Example | When to use | Permission requirement |
|---|---|---|---|
Execute directly with ./ | ./hello.sh | Use when the script has a suitable shebang and should run as a program. | Executable permission is required. |
| Run using Bash | bash hello.sh | Use when you want to select Bash explicitly or test a file without changing permissions. | Executable permission is not required for the script file. |
Run using sh | sh hello.sh | Use only when the script is written for the features supported by that shell. | Executable permission is not required for the script file. |
Running a Bash script with sh can cause errors if it uses Bash-specific syntax. Prefer the intended shebang and Bash when the script targets Bash, or write strictly portable POSIX shell code if portability is required.
Good Script-Writing Practices
- Use clear variable names such as
user_nameinstead of vague names such asx. - Use meaningful filenames that describe the script's purpose.
- Indent commands inside
ifblocks so the structure is easy to see. - Add brief comments beginning with
#when they clarify a non-obvious purpose. The shebang is also a line beginning with#, but it has special meaning on the first line. - Use
read -rfor ordinary literal input and quote text variable expansions such as"$name". - Do not execute scripts from untrusted sources. Read and understand a script before running it, especially if it changes files, installs software, or uses elevated privileges.
- Keep the interpreter in mind: Bash syntax and POSIX shell syntax are related but not identical.
Troubleshooting Common Problems
Permission denied with ./script-name
The file probably lacks executable permission. Add it and try again:
chmod +x script-name
./script-name
Command not found when using only the filename
The current directory is usually not in PATH. Run the script with its relative path:
./script-name
Alternatively, invoke the interpreter:
bash script-name
Variable output is empty or unexpected
Check that assignment uses no spaces around the equals sign and that the variable is referenced with $ or braces:
name="Ada"
echo "$name"
name = "Ada" is not a variable assignment in shell syntax.
Input containing spaces or backslashes is handled unexpectedly
Use read -r and quote expansions:
read -r name
echo "$name"
An if statement reports a syntax error
Check the complete structure, including the spaces in the test expression and the closing fi:
if [ -z "$name" ]; then
echo "No name"
else
echo "Name: $name"
fi
The script behaves differently with sh
The selected interpreter may not support Bash-specific syntax. Run the script with Bash when it targets Bash:
bash script-name
For portability, restrict the script to POSIX shell features and test it with the intended shell.
Exam-Relevant Notes
- A shell script is a text file containing commands executed in sequence.
- The shebang, such as
#!/bin/bash, belongs on the first line and identifies the interpreter for direct execution. chmod +x fileadds executable permission;./fileruns an executable file from the current directory.bash fileruns the file through Bash without requiring executable permission on the file.- Assignments use
name=value, while references use$nameor${name}. read -r nameaccepts user input and stores it inname.- An if statement uses
if,then, optionalelse, and closingfi. Quote variables in test expressions.
For the next steps, continue with shell scripting topics such as arguments, loops, functions, debugging, and scheduling.