keepcalculator

06 Numbers and Powers

Unix Shell Scripting: A Beginner’s Guide

Card No. 06·32938 · Updated · Standard formula, shown below

Avg time per command 6.00 s
Total minutes
1.00 min
Result
Script runtime (s)
60 s
You entered
Number of commands
10
You entered
You enter
Script runtime (s), Number of commands
You get
Avg time per command, Total minutes
Rounding
2 dp

Unix shell scripting is the practice of writing a series of commands in a file that the Unix shell executes sequentially, letting you automate repetitive tasks, combine existing tools, and manage system operations without manual typing. This guide explains what shell scripts are, how they work, and how to write your first ones safely and effectively.

What Is a Shell Script?

A shell script is a plain-text file that contains a sequence of Unix commands. When you run the file, the shell (the program that interprets your typed commands) reads each line and executes it as if you had typed it at the prompt. This turns a manual, error-prone process into a single, repeatable action.

Scripts are used for everything from simple file backups to complex system administration tasks. They are the glue that connects separate utilities like grep, awk, sed, and find, each of which does one thing well. By combining them, you can build powerful pipelines that process data, monitor logs, or deploy software.

Which Shell Should You Use?

The most common Unix shell is Bash (Bourne Again Shell), which is the default on most Linux distributions and macOS. Other shells include sh (the original Bourne shell), zsh (default on macOS since Catalina), ksh, and fish. For beginners, Bash is the best choice because it is widely documented, compatible with sh, and installed almost everywhere.

To see which shell you are using, type:

echo $SHELL

Your scripts should start with a shebang line that tells the system which interpreter to use:

#!/bin/bash

This line must be the first line of the file. It is not a comment; it is an instruction to the kernel.

How to Write and Run a Basic Script

Creating a script is straightforward. Use any text editor (like nano, vim, or gedit) to create a file, then make it executable with chmod.

  1. Create a file, e.g., hello.sh.
  2. Add the shebang line and a command:
#!/bin/bash
echo "Hello, world!"
  1. Save the file and make it executable:
chmod +x hello.sh
  1. Run it:
./hello.sh

The ./ tells the shell to look in the current directory. If you omit it, the shell searches your PATH, which usually does not include the current directory for security reasons.

Variables and User Input

Variables store data that your script can reference. To assign a value, use the equals sign without spaces:

name="Alice"
echo "Hello, $name"

To read input from the user, use read:

echo "What is your name?"
read name
echo "Hello, $name"

You can also use positional parameters: $1, $2, etc., represent the arguments passed to the script. For example, if you run ./greet.sh Bob, then $1 is Bob.

Conditionals and Loops

Most useful scripts make decisions and repeat actions. The if statement checks a condition:

if [ $1 -gt 10 ]; then
  echo "Big number"
else
  echo "Small number"
fi

Note the spaces inside the brackets and the semicolon before then. The -gt means “greater than”; other common comparisons are -lt (less than), -eq (equal), and -ne (not equal).

Loops repeat commands. A for loop iterates over a list:

for file in *.txt; do
  echo "Processing $file"
done

A while loop continues while a condition is true:

count=1
while [ $count -le 5 ]; do
  echo "Count: $count"
  count=$((count + 1))
done

Common Mistakes and Debugging

Beginners often trip over a few recurring issues:

  • Spaces around equals signs: In variable assignments, name = "Alice" is wrong; it must be name="Alice".
  • Missing shebang: Without it, the system may use the wrong shell, causing syntax errors.
  • File not executable: If you get “Permission denied”, run chmod +x script.sh.
  • Wrong line endings: If you edit on Windows, the file may have CRLF endings, which break scripts. Convert to LF or use dos2unix.

To debug, run your script with bash -x script.sh. This prints each command before executing it, showing exactly where it fails.

Safety and Good Practices

Shell scripts can delete or overwrite files, so caution is essential. Always test on dummy files first. Use set -e at the top of your script to make it exit immediately if any command fails, and set -u to treat unset variables as errors. Quote your variables ("$file") to handle spaces in filenames correctly.

Another good habit is to add comments explaining what each section does. Your future self will thank you. Also, avoid using rm -rf with variables unless you are absolutely sure the variable is set; an empty variable can lead to deleting the wrong directory.

Alternatives and When Not to Use Shell

Shell scripting is not always the right tool. For heavy text processing, awk or perl may be better. For complex logic or data structures, Python or Ruby are more maintainable. Shell scripts are best for gluing commands, managing files, and automating short system tasks.

If you need to parse JSON or XML, use a dedicated tool like jq or xmllint rather than trying to do it with regex. Also, never use shell for arithmetic with floating-point numbers; use bc or awk instead.

Frequently Asked Questions

How do I make a script runnable from anywhere?

Move the script to a directory in your PATH, like /usr/local/bin (for system-wide) or ~/bin (for your user). Then you can run it by name from any directory. Make sure it is executable and has the correct shebang.

What is the difference between sh and bash?

sh is the Bourne shell, a simpler and older shell. bash is a superset that adds features like arrays, arithmetic expansion, and improved [[ ]] conditionals. If you write for sh, your script will run in any POSIX shell, but you lose Bash-specific features.

Why do I get “bad interpreter: No such file or directory”?

This usually means the shebang line points to a non-existent interpreter, or the file has Windows line endings. Check the first line and convert the file to Unix format with dos2unix or sed -i 's/\r$//' script.sh.

Can I run a shell script on Windows?

Yes, using Windows Subsystem for Linux (WSL) or tools like Git Bash and Cygwin. The script must be compatible with the Unix environment, and you may need to adjust paths and line endings.

How do I pass arguments to a script?

Arguments are accessed as $1, $2, etc. $# gives the number of arguments, and $@ refers to all of them. For example, ./myscript.sh arg1 arg2 makes $1 equal to arg1.

What does chmod +x do?

It adds the execute permission to the file, allowing the system to run it as a program. Without it, you get “Permission denied” when trying to execute the script directly.

Related

Formula used
in t | Script runtime (s) | s | 60 | 0 | 86400
in n | Number of commands | - | 10 | 1 | 1000
out avg | Avg time per command | s | t / n | 2
out total_min | Total minutes | min | t / 60 | 2

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →