keepcalculator

06 Numbers and Powers

Bash Shell Scripting: Quick Guide & Basics

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

This quick guide explains what bash shell scripting is and how to write your first scripts. You’ll learn the core syntax, variables, conditionals, loops, and functions, plus common pitfalls and best practices—enough to start automating tasks on Linux, macOS, and Windows Subsystem for Linux.

What Is Bash and Why Script It?

Bash (Bourne Again SHell) is the default command-line interpreter on most Linux distributions and macOS. A bash script is a plain-text file containing a sequence of commands that the shell executes. Scripting lets you combine commands, add logic, and automate repetitive tasks—like file backups, system monitoring, or batch renaming—without manual typing each time.

Scripts are also portable: a well-written bash script runs on any system with bash installed, making it a valuable skill for system administrators, developers, and data analysts.

Setting Up Your First Script

To create a bash script, follow these steps:

  1. Open a text editor (e.g., nano, vim, or any GUI editor).
  2. Start the file with a shebang line: #!/bin/bash. This tells the system which interpreter to use.
  3. Write your commands, each on a new line.
  4. Save the file with a .sh extension (optional but conventional).
  5. Make it executable: chmod +x script.sh.
  6. Run it: ./script.sh or bash script.sh.

Example of a minimal script:

#!/bin/bash
echo "Hello, world!"

When you run it, it prints Hello, world! to the terminal.

Variables and Data Types

Bash variables are untyped—everything is stored as a string. To assign a value, use variable=value (no spaces around the equals sign). To read it, prepend a dollar sign: $variable.

Examples:

name="Alice"
age=30
echo "$name is $age years old"

You can also capture command output using command substitution: current_dir=$(pwd). Arithmetic is done with $((...)): sum=$((2 + 3)).

Special variables include $0 (script name), $1, $2 (positional parameters), $# (number of arguments), and $? (exit status of last command).

Conditionals and Loops

Conditionals use the if statement. The syntax is:

if [ condition ]; then
    commands
elif [ other_condition ]; then
    commands
else
    commands
fi

Common test operators include -eq (equal), -ne (not equal), -lt (less than), -gt (greater than), -f (file exists), and -d (directory exists). For string comparison, use = and !=.

Loops come in two main forms:

  • For loop: for i in 1 2 3; do echo $i; done
  • While loop: while [ condition ]; do commands; done

Example that renames all .txt files to .bak:

for file in *.txt; do
    mv "$file" "${file%.txt}.bak"
done

Functions and Script Structure

Functions group reusable code. Define them with function_name() { ... } or function function_name { ... }. Call them just by name.

greet() {
    echo "Hello, $1!"
}
greet "World"

Good practice is to structure scripts into sections: shebang, configuration variables, function definitions, and main logic. Use set -e to exit on any error, and set -u to treat unset variables as errors—these catch many bugs early.

Common Mistakes and How to Avoid Them

Beginners often trip on these pitfalls:

  • Spaces in assignments: name = "Alice" is wrong; remove spaces.
  • Quoting variables: Always quote "$var" to prevent word splitting and glob expansion, especially when filenames contain spaces.
  • Using == in [ ]: In the test command, use = for strings, not == (though == works in some shells).
  • Forgetting the fi, done, or esac: Every if needs a fi, every for a done, every case an esac.
  • Not making the script executable: You’ll get a permission denied error if you forget chmod +x.

Debugging and Testing

To debug, run your script with bash -x script.sh—this prints each command before executing it. You can also insert set -x inside the script to turn on tracing, and set +x to turn it off. Add echo statements to inspect variable values.

Test with sample inputs and edge cases: empty strings, missing files, and unexpected arguments. Use shellcheck, a static analysis tool, to catch common issues automatically.

Alternatives and When Not to Use Bash

Bash is excellent for glueing commands and file manipulation, but it’s not ideal for complex data processing or performance-critical tasks. Alternatives include:

  • Python: Better for complex logic, data structures, and cross-platform GUI or network tasks.
  • Perl: Strong text processing, though less common now.
  • PowerShell: The default on Windows, with object-based pipelines.

If you find yourself writing hundreds of lines of bash with nested loops and arithmetic, consider moving to a more robust language. For simple automation, bash remains the fastest and most universal choice on Unix-like systems.

Frequently Asked Questions

How do I run a bash script without making it executable?

You can run it with bash script.sh—this invokes bash directly and doesn’t require the executable permission. This is handy for quick tests, but for regular use, it’s better to make it executable and run it as ./script.sh.

What is the difference between bash script.sh and ./script.sh?

bash script.sh runs the script in a new bash process, ignoring the shebang line (though it’s still good practice to have it). ./script.sh uses the interpreter specified in the shebang. If the shebang points to a different shell (e.g., #!/bin/sh), the behavior may differ.

How can I pass arguments to a bash script?

Arguments are accessed as $1, $2, etc. For example, if you run ./script.sh foo bar, then $1 is foo and $2 is bar. Use $@ to refer to all arguments, and $# for the count.

What does set -e do?

set -e makes the script exit immediately if any command returns a non-zero exit status. This prevents the script from continuing after an error, which is often desirable. However, be careful: it can cause unexpected exits in loops or with commands that legitimately return non-zero (like grep when no match is found).

How do I read user input in a script?

Use the read command. For example: read -p "Enter your name: " name stores the input in the variable name. The -p flag displays a prompt.

Can I use bash on Windows?

Yes, via Windows Subsystem for Linux (WSL), which provides a full Linux environment. Alternatively, you can use Git Bash or Cygwin, which offer bash-compatible environments without a full Linux kernel.

Related

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 →