Introduction to Linux Shell Scripts

Learn what Linux shell scripts are, how Bash interprets them, and how to create, run, troubleshoot, and safely maintain basic scripts.

A shell script is a plain-text program containing instructions for a command shell. The shell reads the instructions and starts commands or other programs in the order written. Instead of typing several terminal commands separately, you can save them in one reusable file.

This lesson uses Bash, the Bourne Again Shell. Bash is widely used on Linux and is both a command interpreter and a scripting language. You should already know how to open a terminal, run basic commands, navigate with cd and pwd, list files with ls, and edit plain-text files.

What Is a Shell Script?

A shell is a command interpreter: it reads commands and starts programs. When you enter ls in a terminal, the shell interprets that command and runs the appropriate program.

A shell script is a plain-text file containing shell-language instructions. A plain-text file contains readable characters rather than word-processor formatting. The script can group commands, variables, functions, comments, and basic input or output into one program.

For example, a script could print the date, show the current directory, and list its files. Running one script then performs the same sequence each time.

Shell scripts are normally interpreted. An interpreter is the program that reads and executes script instructions while the script runs. A compiled program, by contrast, is transformed ahead of time into machine code or another executable form by a compiler. Shell scripts are convenient to edit and inspect, while compiled programs can offer different performance and distribution characteristics.

Why Use Shell Scripts?

  • Automation: repeated tasks can be performed with one command.
  • Less manual typing: you do not need to re-enter a long series of commands.
  • Repeatability: the same steps can be performed in the same order.
  • Consistency: a saved procedure reduces errors caused by forgetting a step or mistyping a command.

Typical uses include collecting system information, processing files, preparing development environments, and performing routine administrative tasks. A script can execute commands from top to bottom, make decisions, repeat actions, and organize reusable operations.

Shells and Scripting Languages

Shell syntax depends on the interpreter selected for the script. Bash is a common choice for Linux examples, but it is not the only Unix shell.

ShellTypical interpreter path or commandGeneral useCompatibility consideration
Bash/usr/bin/env bash or bashCommon Linux shell and beginner scripting languageBash features are not guaranteed to work in other shells
kshkshKorn shell and its scripting dialectSimilar in some areas to other Bourne-style shells, but do not assume complete compatibility
tcshtcshC-shell-derived interactive shell and scripting languageIts scripting syntax differs substantially from Bash
shshOften used for portable shell scriptsIt may not support Bash-specific syntax

Select the shell deliberately. A Bash script may use features such as arrays or particular forms of conditional syntax that do not work when the file is run with sh, ksh, or tcsh. The command used to start the script must match the syntax used inside it.

Parts of a Shell Script

  • Commands: instructions such as echo, date, pwd, and ls. They normally execute in sequence.
  • Comments: explanatory text beginning with #. The shell normally ignores comments.
  • Variables: named values that store information for later use.
  • Functions: named, reusable groups of commands.
  • Input and output: scripts can read values and display text with commands such as echo or printf.

Create a Basic Bash Script

Create a known working directory, then open a plain-text editor. For example:

mkdir -p ~/shell-practice
cd ~/shell-practice
nano hello.sh

The conventional .sh suffix is helpful because it identifies a shell script, although the suffix is not required by Linux. Enter this content:

#!/usr/bin/env bash
# Print a harmless greeting.
echo "Hello from Bash!"

The first line is the shebang: the #! declaration at the beginning of a script that identifies its intended interpreter. Here, /usr/bin/env bash finds Bash through the user's PATH. The PATH is the list of directories searched when you enter a command name.

Save the file as hello.sh. In Nano, you can save with Ctrl+O, confirm the filename, and exit with Ctrl+X.

Run a Script

You can invoke Bash explicitly:

bash hello.sh

This tells Bash to read and execute the file. The file does not need executable permission for this method.

To execute the file directly, first grant it executable permission with chmod:

chmod +x hello.sh
ls -l hello.sh
./hello.sh

chmod changes file permissions. The +x option adds the executable permission. The command ls -l hello.sh lets you inspect the permissions; an executable file normally shows an x in its permission string.

The ./ means “from the current directory.” The current directory is the directory in which the shell is presently operating. Linux usually does not search the current directory when you enter only a filename, because doing so could accidentally run an untrusted file. Therefore, use ./hello.sh for a script in the current directory, or use its absolute path.

MethodExample commandRequires executable permissionUses shebangWhen to use it
Explicit interpreterbash hello.shNoNo; Bash is selected by the commandTesting a Bash script or choosing the interpreter explicitly
Relative direct execution./hello.shYesYesRunning an executable script in the current directory
Absolute direct execution/home/user/shell-practice/hello.shYesYesRunning a script when its full location is known

A Multi-Command Example

The following script uses safe, read-only commands and demonstrates execution order:

#!/usr/bin/env bash
# Show basic information about the current location.
echo "Current date and time:"
date

echo "Current directory:"
pwd

echo "Files here:"
ls

When you run this script, Bash starts with the echo command, then runs date, then pwd, and finally ls. Blank lines and comments improve readability but do not change the order of commands.

Variables

A variable is a named value used by a script. In Bash, assign a value with no spaces around the equals sign, then expand the value with $name or ${name}:

#!/usr/bin/env bash
name="Ada Lovelace"
echo "Hello, ${name}!"

Quotes are important when a value contains spaces. The assignment name="Ada Lovelace" stores the complete value. Quoting an expansion, as in "${name}", helps keep the value together when it is passed to a command.

#!/usr/bin/env bash
folder="shell practice"
echo "The folder is: ${folder}"

Common mistakes include writing name = "Ada", which Bash does not interpret as a variable assignment, or writing echo "Hello, name", which prints the word name instead of its value.

Functions

A function is a named, reusable group of script commands. Define it once and call it by name:

#!/usr/bin/env bash

show_location() {
    echo "You are working in:"
    pwd
}

show_location

When Bash reaches show_location, it runs the commands inside the function from top to bottom. Functions keep repeated logic organized and make larger scripts easier to maintain.

Interpreter Selection and Portability

When a script is executed directly, its shebang indicates the intended interpreter. For a Bash script, use a Bash shebang such as:

#!/usr/bin/env bash

A shebang does not convert one shell language into another. If a script contains Bash-specific syntax, running it as sh script.sh may produce syntax errors or different behavior. Likewise, Bash syntax should not be assumed to work in ksh or tcsh.

  • Use a Bash shebang and run the script with Bash when the script is written for Bash.
  • Use syntax supported by the selected shell when portability is important.
  • Do not assume the interactive shell configured for your account is the interpreter used by every script or scheduled task.

Basic Safety and Maintainability

  • Use comments to explain purpose, assumptions, and unusual commands.
  • Choose meaningful names such as backup_directory instead of vague names such as x.
  • Test on harmless input and in a practice directory before using a script on important files.
  • Review commands that delete, overwrite, move, change permissions, or affect many files.
  • Do not embed passwords, access tokens, private keys, or other secrets directly in a script.
  • Keep scripts focused and use functions when a group of commands represents one reusable task.

Troubleshooting

Permission denied with ./script.sh

The execute bit may not be set, or the file or directory permissions may prevent access. Check the permissions and add execute permission:

ls -l script.sh
chmod +x script.sh
./script.sh

When appropriate, you can alternatively run it through Bash:

bash script.sh

Command not found when entering the filename

The current directory is usually not included in PATH. Entering script.sh asks the shell to search the directories in PATH, not necessarily the directory you are currently viewing. Run a local executable with:

./script.sh

Adding the current directory globally to PATH is generally undesirable because it can make it easier to run an unintended file.

Syntax errors or the wrong shell

Check whether the script has an appropriate shebang and whether it is being started with the intended interpreter. A Bash-specific script should be tested with:

bash script.sh

If direct execution behaves differently, inspect the shebang and executable permission. Do not run a Bash script with sh unless its syntax is compatible with the available sh.

Unexpected variable output

  • Remove spaces around the assignment operator: use name="value", not name = "value".
  • Expand the variable with $name or ${name}.
  • Quote values and expansions when they may contain spaces: folder="${folder}".

Interpreter errors after editing on another operating system

Different operating systems can use different line endings. A script containing incompatible line endings may report an interpreter error even when the shebang looks correct. Save or convert the file using Unix LF line endings, then try the script again.

Complete Beginner Workflow

  1. Create a practice directory with mkdir -p ~/shell-practice.
  2. Change into it with cd ~/shell-practice.
  3. Create a plain-text file with nano info.sh.
  4. Add #!/usr/bin/env bash, comments, and safe commands.
  5. Test it explicitly with bash info.sh.
  6. Review the output and the commands.
  7. Use chmod +x info.sh if you want direct execution.
  8. Run it as ./info.sh.

For further study, continue with shell scripting topics such as variables, functions, redirection, debugging, and scheduling.

Exam-Relevant Notes

  • A shell script is a plain-text program interpreted by a shell.
  • Bash is a shell and a scripting language; its syntax is not identical to sh, ksh, or tcsh.
  • The shebang begins with #! and identifies the interpreter for direct execution.
  • bash script.sh invokes Bash explicitly and does not require executable permission.
  • chmod +x script.sh adds executable permission, allowing direct execution such as ./script.sh.
  • The current directory usually requires ./ because it is not normally searched through PATH.
  • Bash variable assignments do not have spaces around =, and variable values are expanded with $.