# Bash script

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/bash-script

## Quick definition

A Bash script is a plain text file with a list of commands that the Bash shell runs one after another. Instead of typing each command separately, you can write them down in a file and run the whole script at once. This makes it easy to automate repetitive tasks, like backing up files or setting up software. You just need to know basic command line operations to get started.

## Simple meaning

Think of a Bash script as a recipe card for your computer. When you cook, you follow a list of steps to turn ingredients into a finished dish. A Bash script does the same thing, but with commands for the computer. For example, if you regularly need to copy a set of files from one folder to another, rename them, and then compress them into a zip file, you could do that manually every time. Or you could create a Bash script that contains those exact steps: 'copy these files', 'rename them like this', 'compress the result'. Then whenever you need that task done, you just double-click the script file or run it from the terminal, and the computer follows the instructions automatically.

Bash is the default command-line interface on most Linux distributions and on macOS. It interprets the commands you type and executes them. A Bash script is simply a collection of those typed commands saved in a file. The file usually has a '.sh' extension, like 'backup.sh'. Inside, each line is a command that you might have typed manually. You can also add logic, such as 'if this condition is true, then do this, otherwise do that'. That makes scripts smarter and able to handle different situations automatically.

Because Bash scripts are just text, they are easy to edit with any text editor. They do not need to be compiled into a different format; the shell reads and runs them directly. This makes them very flexible and a common tool for system administrators, DevOps engineers, and anyone who works with servers or automation. They help you avoid human error by performing the same steps the same way every time, and they save huge amounts of time, especially when dealing with many files or complex sequences of commands.

## Technical definition

A Bash script is an executable text file that contains a series of commands interpreted by the GNU Bourne Again SHell (Bash), the default shell on most Unix-like operating systems. The script typically starts with a shebang line (`#!/bin/bash`) which tells the system which interpreter to use. The file must have execute permissions (set via `chmod +x script.sh`) to run directly. Bash scripts support variables, control structures (if/else, for, while, case), functions, arrays, input/output redirection, and command substitution. They can call any command available in the shell environment, including built-in commands (like `cd`, `echo`, `exit`) and external utilities (like `grep`, `sed`, `awk`, `find`).

Execution of a Bash script triggers a new subshell process unless the script is sourced (using `source script.sh` or `. script.sh`). In a subshell, changes to environment variables or the current working directory do not affect the parent shell. Sourcing runs the script in the current shell context, preserving changes. Scripts can accept positional parameters (`$1`, `$2`, etc.) and special variables like `$@` (all arguments), `$#` (number of arguments), and `$?` (exit status of the last command). Exit status values are integers: 0 typically indicates success, and non-zero values indicate errors, which allows conditional logic.

Real IT implementation often involves scripting for system maintenance tasks like log rotation, user account management, service restarts, software installation, backups, and monitoring. Configuration management tools like Ansible, Chef, and Puppet often use Bash scripts as building blocks. In DevOps pipelines, Bash scripts are used to set up environments, run tests, and deploy artifacts. They are also fundamental in cloud infrastructure through user-data scripts on cloud instances, where a Bash script runs at first boot to configure the machine automatically. Security considerations are critical: script injection attacks can occur if user input is not properly sanitized, and scripts should avoid hard-coding passwords or using `eval` on untrusted data. Debugging is done with `set -x` to print each command before execution, or `set -e` to exit on first error. Linting tools like ShellCheck help identify syntax errors and potential pitfalls.

## Real-life example

Imagine you are responsible for a small office’s daily backup routine. Every evening, you need to copy important files from several employees' shared folders to an external drive, then compress them with a date stamp, and finally send a confirmation email to your manager. Doing this manually could take 15 minutes each day, and you might forget a step or make a typo. Instead, you could write a Bash script that does everything for you.

Let’s map this to IT: The shared folders are like directories on a server. The external drive is a mount point. The date stamp is generated by the `date` command. The compression uses `tar` or `zip`. The email can be sent using a command-line tool like `mail` or `mutt`. The script would start with a shebang, then use `cp` or `rsync` to copy the folders, run `tar` to compress, and then pipe the result to the mail command. You can add a check: if the compression fails, send an alert instead of the normal email.

By saving this script as `backup.sh` and setting it as a cron job to run every evening at 6 PM, the entire process becomes automatic. You no longer need to be physically present or remember the steps. The script handles errors, logs the output, and ensures consistency. If you later need to change the backup source or destination, you just edit the text file. This analogy shows how a Bash script takes a repetitive, error-prone manual process and turns it into a reliable, automated routine.

## Why it matters

Bash scripting is a foundational skill for any IT professional working with Linux or Unix systems. It allows you to automate routine tasks, reduce human error, and significantly improve operational efficiency. Without scripting, system administrators would need to manually type every command for every repetitive task, which is slow, boring, and error-prone. With Bash, you can write a script once and run it hundreds of times, ensuring consistent results. For example, when you need to check the disk usage on 50 servers, a Bash script can loop through a list, run `df -h` on each, and collect the output into a single report.

In the world of DevOps and cloud computing, Bash scripts are essential for infrastructure as code. Tools like Terraform and Ansible often invoke Bash scripts to perform initial setup, install software, or configure services on virtual machines. When you launch a new server in AWS or Azure, you can pass a Bash script as user-data that runs automatically at boot to install packages, set up users, and configure the application. This makes scaling from one server to hundreds consistent and manageable.

Bash scripting is a key component of many exam objectives for CompTIA Linux+, Red Hat Certified System Administrator (RHCSA), and Linux Professional Institute (LPI) certifications. Mastering Bash scripts demonstrates that you understand how the operating system works at a deeper level. You not only know what commands do but how to combine them to solve real problems. This skill sets you apart from technicians who only know how to click through graphical interfaces. It shows you can think logically, debug issues, and automate solutions, all critical abilities in IT operations.

## Why it matters in exams

Bash scripting appears in several major IT certification exams, most notably the CompTIA Linux+ (XK0-005), Red Hat Certified System Administrator (RHCSA), and Linux Professional Institute (LPIC-1). In these exams, scripting is not just an optional topic; it is a core objective. For example, in the CompTIA Linux+ exam, objective 1.3 asks candidates to 'create and manage shell scripts' including use of variables, loops, conditionals, and error handling. Questions may ask you to read a script and determine its output, identify what a given command does inside a script, or write a small script to accomplish a task. The RHCSA exam often requires you to create a script that sets up a user, configures a service, or performs a specific file operation. You are expected to write the script during the performance-based exam.

The LPIC-1 exam 102 covers shell scripting in depth, including topics like script debugging, using positional parameters, and creating simple functions. Questions can be scenario-based where you need to choose the correct script fragment from multiple choices. They also test knowledge of special variables like `$?`, `$0`, and `$#`. Understanding how to use `if`, `for`, `while`, and `case` constructs is essential. You may be given a script with an error and asked to identify the fix.

Beyond Linux-focused exams, the AWS Certified SysOps Administrator and AWS Certified Solutions Architect exams may include Bash scripting in the context of EC2 user-data scripts or AWS Lambda using Bash runtime. While not a primary focus, questions about automating instance configuration often rely on understanding scripting basics. The Cisco Certified Network Associate (CCNA) traditionally does not include Bash scripting, but if you work with network automation using Python or Ansible, you may encounter Bash commands executed from those tools. The CompTIA Security+ exam rarely asks directly about Bash scripting, but knowing how to analyze a script can be helpful in the context of interpreting malicious scripts or log files.

## How it appears in exam questions

In certification exams, Bash scripting questions appear in multiple formats. The most common are multiple-choice questions that give you a short script and ask about the output or the purpose. For example, you might see a script that uses a `for` loop to rename files, and you have to say what the renamed files will be called. Another pattern is giving a script with a logical error and asking which line needs to be changed. In the RHCSA performance-based exam, you might be asked to 'write a script that takes a username as an argument, creates that user, sets a password, and adds the user to the wheel group'. You would need to write the script from scratch in the terminal.

Another common type is the 'fill in the blank' or 'choose the correct command' question. They might show a script that is supposed to check if a file exists and then delete it, but the condition is missing the proper test command. You would choose `if [ -f /tmp/file.txt ]; then` over incorrect alternatives like `if ( -f /tmp/file.txt )` or `if testfile /tmp/file.txt`. Troubleshooting questions often involve a script that is supposed to run daily but fails due to a missing shebang or incorrect permissions. You would need to identify that the file lacks execute permissions or the shebang is misspelled, like `#!/bin/bash` missing the leading `#!` or pointing to a non-existent shell.

Scenario-based questions may describe a system administrator who needs to automate user account cleanup every month. The script is provided, and you need to determine why it does not delete users who have been inactive for over 90 days. The answer might be that the script uses the wrong date comparison, or that it does not iterate over all users. These questions test your ability to read and reason about actual script behavior, not just memorize syntax. Some exams also include command-line questions where you must type the correct command or script snippet into a simulated terminal. For instance, you might be asked to 'write a one-line command that finds all .log files older than 7 days and compresses them'. That combines understanding of `find` and `gzip` with the ability to construct a shell pipeline.

## Example scenario

You are a junior system administrator at a medium-sized company. The company has a shared web server where developers upload static HTML files for testing. Over time, the temporary folder `/tmp/web_staging` accumulates hundreds of old files, and disk space is running low. Your manager asks you to create a process that automatically cleans up files older than 7 days from that folder every night.

You decide to write a Bash script to do this. First, you open a text editor and create a file called `cleanup_temp.sh`. You type the shebang line `#!/bin/bash`. Then you add a comment like `# Remove files older than 7 days from /tmp/web_staging`. Next, you write the main command: `find /tmp/web_staging -type f -mtime +7 -exec rm {} \;`. This is a critical command: `find` locates files, `-type f` ensures only files (not directories) are considered, `-mtime +7` selects files modified more than 7 days ago, and `-exec rm {} \;` deletes each one. You also add a safety check: `if [ -d /tmp/web_staging ]; then` before running the find, to avoid errors if the folder was deleted.

After saving the file, you make it executable with `chmod +x cleanup_temp.sh`. You test it by creating a dummy file with a modification date of 10 days ago using `touch -t 202503101200 dummy.txt` and then running the script. The file is successfully removed. Finally, you set up a cron job by typing `crontab -e` and adding the line `0 2 * * * /home/admin/cleanup_temp.sh` to run it every night at 2 AM. Your manager is pleased because the task now happens automatically, and the server’s disk stays healthy without manual intervention.

## The Shebang Line and Bash Script Execution Context

In Bash scripting, the very first line of the script typically begins with a shebang (#!) followed by the path to the interpreter, such as #!/bin/bash. This tells the operating system which shell should execute the script. The shebang is critical because it ensures the script runs under the correct environment, especially when multiple shells are available. For example, a script intended for Bash will fail if executed under a different shell like sh or dash without proper shebang. Exam questions often test knowledge of shebang syntax, the difference between /bin/bash and /usr/bin/env bash, and how the kernel reads this line. Use /usr/bin/env bash for portability, as it finds bash in the user's PATH. The shebang line also influences script behavior regarding debugging, because bash ignores the shebang only when the script is sourced, not executed as a standalone.

Execution requires the file to have executable permissions set with chmod +x script.sh. Without this, you must run the script with bash script.sh, which bypasses the shebang entirely. Understanding how the PATH variable and current working directory interact is crucial: scripts in the current directory require ./ prefix (e.g., ./myscript) unless the directory is in PATH. Exams test these details because misconfigurations cause common runtime errors. The shebang may also include options like #!/bin/bash -x for debugging mode, which prints each command before execution. This is a frequent exam point-candidates must recognize that -x (xtrace) is a runtime option, not part of the command logic. Another nuance is that comments after the shebang on the same line are not standard; the shebang must be the exact first two bytes of the file. Knowledge of these specifics distinguishes competent scripters from novices.

File permissions, relative vs absolute paths, and the exec system call behind script execution are all foundational. The shebang line is processed by the kernel via the exec system call; if it points to a non-existent interpreter, the script fails with 'command not found.' Exams often present debugging scenarios where a script works when invoked with bash but fails when executed directly-testing shebang correctness. Also, the shebang line length is limited on some systems, so extremely long interpreter paths can be truncated. For IT certification exams, remembering that #!/bin/bash is the most common, but #!/usr/bin/env bash is preferred for cross-platform portability, is a key differentiator. Scripts not starting with a shebang run in the calling user's current shell, which may not be bash, leading to unintended behavior. So the shebang is not a mere formality but a fundamental execution control mechanism.

Finally, scripts used in cron jobs or systemd services often lack a terminal and may require explicit shebangs and absolute paths to commands. The shebang line also interacts with the kernel's binfmt_misc system, which can handle scripts with unusual interpreters. Exam questions sometimes ask what happens when a script is sourced versus executed: sourcing does not spawn a new process and ignores the shebang, so variables persist. This is a critical concept for debugging and configuration management. Understanding the shebang and execution context ensures correct script deployment in production environments.

## Error Handling and Exit Codes in Bash Scripts

Robust Bash scripts must handle errors gracefully. Unlike higher-level languages, Bash does not halt on errors by default; a failed command continues the script, potentially leading to data corruption or unexpected states. The exit code of the last command is stored in the $? variable, where 0 indicates success and any non-zero value indicates failure. Exams test the understanding of $? and how to use it conditionally. For example, testing $? after a command lets you branch on success or failure. However, direct use of $? is considered fragile; modern scripts prefer using if command; then to check success directly. The set -e option (errexit) causes the script to exit immediately if any command returns a non-zero exit code, which is a common exam topic. But set -e has pitfalls: it does not apply inside conditionals (if/while/until) or to commands in a pipeline, which can mislead candidates.

More advanced error handling includes set -u (nounset) that treats undefined variables as errors, and set -o pipefail that makes a pipeline fail if any component fails. These three-set -euo pipefail-form the gold standard for production scripts. Interview questions and exams often ask why these are important: they prevent silent failures and cascading damage. The trap command is another powerful error-handling tool: trap 'cleanup' EXIT ensures a function runs when the script exits, regardless of success or failure. trap 'echo error on line $LINENO' ERR runs on any error if set -e is not used. Knowing how to send trap signals (EXIT, ERR, RETURN, DEBUG) is essential for certifications. Common exam examples involve cleaning up temporary files or releasing resources.

Exit codes beyond the conventional 0-255 range are truncated, so use only values 0-127 for custom codes; 128+ are used by signals. For instance, exit 1 is generic failure, exit 2 is misuse of shell builtins (like missing keyword), exit 126 is not executable, exit 127 is command not found. Exams test these standard codes to identify failure types. The special variable $? must be checked immediately because any subsequent command overwrites it. Also, scripts should override the default exit code if called in a function using return statements. The explicit exit command in a script sets the script's exit code, which is important for parent processes (like CI pipelines) that rely on exit status.

Another key concept is using && and || for conditional execution: command1 && command2 runs command2 only if command1 succeeds; command1 || command2 runs command2 only if command1 fails. This is a concise way to manage error flow without if statements. Exams often pose scenarios where a missing file or directory causes a script to proceed incorrectly; candidates must propose proper use of test constructs ([ -f file ]) or directory existence checks before operations. The errexit option behaves differently in subshells-a command inside ( ) or $( ) may not trigger exit if the subshell's exit code is ignored. Understanding these subtleties makes the difference between a fragile script and a resilient one.

Finally, debugging errors with set -x (xtrace) prints commands and their arguments as they execute, which is invaluable for troubleshooting. Combined with trap 'echo $BASH_COMMAND failed' ERR, developers can isolate the exact failure point. For certification exams, you must know that run-time errors (like permission denied or broken pipe) cause exit codes, but syntax errors in the script itself prevent execution entirely. Writing scripts that check for command availability, validate input parameters, and use proper quoting to handle spaces and special characters is also part of error handling. The ability to anticipate and manage failures-not just avoid them-is a core skill tested in general IT certifications.

## Common mistakes

- **Mistake:** Forgetting the shebang line at the beginning of the script.
  - Why it is wrong: Without the shebang, the system does not know which interpreter to use. It may default to another shell or fail to run. Many modern systems will still run the script with the default shell, but the behavior can be unpredictable.
  - Fix: Always start your script with `#!/bin/bash` or `#!/usr/bin/env bash` to explicitly specify the Bash interpreter.
- **Mistake:** Not making the script file executable after creation.
  - Why it is wrong: If the file does not have execute permission, running it with `./script.sh` will return 'Permission denied'. You can only run it by invoking `bash script.sh`, which may not work in all automated contexts like cron jobs.
  - Fix: After creating the script, run `chmod +x script.sh` to add execute permission for the owner.
- **Mistake:** Using spaces around the equal sign when assigning a variable.
  - Why it is wrong: In Bash, `name = "value"` is interpreted as a command `name` with two arguments `=` and `"value"`, which is a syntax error. The correct syntax has no spaces: `name="value"`.
  - Fix: Write variable assignments without spaces around the equals sign: `myvar="Hello"`.
- **Mistake:** Not quoting variables, leading to word splitting or globbing issues.
  - Why it is wrong: If a variable contains spaces or special characters (like `*`), using it unquoted can break the command. For example, `rm $file` could delete unintended files if `$file` expands to `*` or contains spaces.
  - Fix: Always double-quote variable expansions: `rm "$file"`. This preserves the variable as a single argument.
- **Mistake:** Using a semicolon instead of a line break to separate commands in a condition.
  - Why it is wrong: The syntax `if [ condition ]; then` is correct, but beginners sometimes write `if [ condition ] then` missing the semicolon or newline before `then`. This causes a syntax error.
  - Fix: Remember the structure: `if [ condition ]; then` (semicolon and space) or put `then` on a new line.

## Exam trap

{"trap":"The exam presents a script that uses `#!/bin/sh` instead of `#!/bin/bash`, and then uses Bash-specific features like `[[ ]]` or arrays. They ask if the script has errors.","why_learners_choose_it":"Learners may not know the difference between `/bin/sh` (often a POSIX shell like dash) and `/bin/bash`. They see no syntax error in the code and assume it will work, because `[[ ]]` looks similar to `[ ]`.","how_to_avoid_it":"Know that `#!/bin/sh` typically refers to the Bourne shell or a POSIX-compliant shell like dash, which does not support `[[ ]]`, arrays, or `source` (use `.` instead). If the script uses these Bash-specific constructs, it will generate errors when run under `/bin/sh`. Always look at the shebang line and know which features each shell supports."}

## Commonly confused with

- **Bash script vs Shell script:** A shell script is a broader term that refers to scripts written for any shell (Bash, Zsh, Ksh, Dash, etc.). A Bash script is a specific type of shell script that is written for the Bash shell. While many shell scripts are Bash-compatible, some scripts use features unique to other shells (like Zsh extended globbing) and will not run correctly under Bash. (Example: A script that uses `echo ${PIPESTATUS[@]}` is Bash-specific and may not work in a plain `sh` environment.)
- **Bash script vs Batch file (.bat or .cmd):** Batch files are scripts for Windows command prompt (cmd.exe) or PowerShell (.ps1). Bash scripts run on Unix-like systems (Linux, macOS, WSL). The syntax is entirely different: batch files use `@echo off`, `%variable%`, and `if exist`, while Bash uses `#!/bin/bash`, `$variable`, and `if [ -f ]`. They are not interchangeable. (Example: A batch file to list files would use `dir`, while a Bash script would use `ls -la`.)
- **Bash script vs Python script:** Python scripts use a completely different syntax and require the Python interpreter. Bash scripts are composed of shell commands, while Python is a full programming language with advanced data structures and libraries. Bash is best for orchestrating system commands, while Python excels at complex logic, text processing, and cross-platform portability. (Example: A Bash script to rename files might use a `for` loop with `mv`, while a Python script would use `os.rename()` and do more complex pattern matching.)

## Step-by-step breakdown

1. **Create the script file** — Use a text editor (nano, vim, VS Code) to create a new file with a `.sh` extension, like `myscript.sh`. The extension is not required but helps identify the file type. Start the file with the shebang `#!/bin/bash` to explicitly specify the interpreter.
2. **Write the commands** — Add the shell commands you want to automate, one per line. For example, `echo "Hello World"`, `cd /etc`, `ls`. You can use variables (e.g., `name="John"`), loops (`for i in 1 2 3; do`), conditionals (`if [ -f file.txt ]; then`), and functions. Each command runs sequentially from top to bottom.
3. **Make the script executable** — Before you can run the script directly, you need to set the execute permission using `chmod +x myscript.sh`. This changes the file mode to allow running it as a program. You can verify with `ls -l`, the permissions should include `x` (e.g., `-rwxr-xr-x`).
4. **Run the script** — Execute the script by typing `./myscript.sh` from the terminal in the same directory. The `./` tells the shell to look in the current directory. Alternatively, you can call the interpreter directly: `bash myscript.sh`. This works even without execute permissions.
5. **Debug and refine** — If the script does not work as expected, run it with debug mode: `bash -x myscript.sh` (or add `set -x` inside the script). This prints each command before it is executed, showing the actual values of variables and expansions. Look for syntax errors or unexpected behavior, fix the script in the text editor, and test again.
6. **Schedule automation (optional)** — Once the script works correctly, you can automate its execution using cron (on Linux) or launchd (on macOS). Edit the crontab with `crontab -e` and add a line like `0 3 * * * /path/to/script.sh` to run it daily at 3 AM. Make sure the script has full paths to commands if needed, as cron runs with a minimal environment.

## Practical mini-lesson

To really understand Bash scripting, you need to go beyond simple one-liners and see how scripts are used in real system administration. Consider a typical scenario: you have to manage user accounts on a Linux server. A Bash script can automate the creation, modification, and deletion of users, ensuring consistency across hundreds of accounts. For instance, you might write a script that reads a CSV file of new employees, then for each line extracts the username, full name, and department, runs `useradd` with appropriate options, assigns a temporary password, and sends an email to the user’s manager. This script would use loops (`while IFS=, read`), conditionals (`if ! useradd ...; then`), and string manipulation (`${username,}` to lowercase).

A practical challenge: what if the script runs at a time when the CSV file is being updated? You need to implement file locking to prevent race conditions. You can use a lock file with `mkdir` (which is atomic) or `flock`. For example, `if mkdir /tmp/script.lock; then ... else ... fi`. Also, the script must log its actions. Professionals use functions like `log() { echo "$(date) $1" >> /var/log/useradmin.log; }`. This helps with auditing and troubleshooting.

Another common pitfall: environment differences. When you run a script from a scheduled task like cron, the PATH environment variable is often very limited. Your script might fail because `useradd` is not found. The fix is to always use full paths to commands (like `/usr/sbin/useradd`) or set the PATH at the start of the script: `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`. Similarly, scripts that rely on the user’s home directory for configuration files may not find them. Always fully qualify paths or use absolute paths for critical resources.

What can go wrong? A common error is not handling non-zero exit statuses. For example, if `useradd` fails because the username already exists, the script might continue silently and attempt to set a password for a non-existent account, leading to partial system state. Professionals use `set -e` to exit on any error, or they explicitly check `if [ $? -ne 0 ]; then echo "Error creating user $user" >> /var/log/error.log; exit 1; fi`. Also, input validation is critical: the script should check that the CSV file exists and has data, and that fields are not empty. Otherwise, you might create users with blank names or passwords. By applying these robust practices, your Bash scripts become reliable, secure, and production-ready.

## Commands

```
#!/bin/bash
```
Shebang line that tells the kernel to use /bin/bash as the interpreter for the script. Must be the first line. Without it, the script may run in a different shell or fail.

*Exam note: Exams test that the shebang must start with #! and be the first line. Also test difference between #!/bin/bash and #!/usr/bin/env bash for portability.*

```
set -euo pipefail
```
Enables three critical safety options: exit on error (-e), treat unset variables as error (-u), and fail pipeline if any component fails (pipefail). Placed at the top of the script after shebang.

*Exam note: Shows understanding of defensive scripting. Exams often ask what each option does and why they are used together.*

```
if [ -f /etc/config.cfg ]; then source /etc/config.cfg; fi
```
Tests if a file exists (-f) and is a regular file before sourcing it. Prevents errors when the file is missing.

*Exam note: Tests file test operators (-f, -d, -e) and the difference between sourcing (.) and executing. Common in configuration handling questions.*

```
trap 'rm -f /tmp/tempfile' EXIT
```
Registers a cleanup action that runs when the script exits, regardless of whether it succeeded or failed. Ensures temporary files are removed.

*Exam note: Exams assess ability to manage signal handling. Trap on EXIT, ERR, or INT are frequent. Know that quotes are necessary to prevent immediate expansion.*

```
while IFS= read -r line; do echo "Line: $line"; done < input.txt
```
Reads a file line by line, triming leading/trailing spaces only when IFS= is set. The -r flag prevents backslash escapes. Used for processing text files.

*Exam note: Tests redirection, IFS usage, and the read command. Exams ask why IFS= is needed and why -r prevents mangling backslashes.*

```
for i in {1..10}; do echo "Count $i"; done
```
Brace expansion loop that iterates over numbers 1 to 10. Outputs each number. Simple but demonstrates bash-specific expansion.

*Exam note: Tests brace expansion versus seq command. Exams note that brace expansion is a bashism and may not work in other shells. Also tests variable substitution inside strings.*

```
export PATH=$HOME/bin:$PATH
```
Prepends a user-specific bin directory to the PATH environment variable, making scripts or binaries in that directory callable by name. The export makes it available to child processes.

*Exam note: Tests understanding of environment variables, export, and PATH order. Exams ask about why export is needed and how to permanently set PATH in .bashrc.*

```
ps aux | grep httpd | awk '{print $2}'
```
Pipes the output of ps to grep for filtering lines containing 'httpd', then uses awk to extract the second column (PID). Common for finding process IDs.

*Exam note: Tests piping, grep, awk field extraction, and process management. Exams ask about pipefail behavior and how to avoid grep itself appearing in results (use grep [h]ttpd).*

## Memory tip

Remember: CHOMPS, Create, Hashbang, chmod, Operate, Mute (debug), Parse, Schedule. Or simpler: 'Shebang then chmod before you run'.

## FAQ

**What is the difference between a Bash command and a Bash script?**

A Bash command is a single instruction you type in the terminal. A Bash script is a file with multiple commands that runs together automatically.

**Do I need to install anything to write Bash scripts?**

No, Bash comes pre-installed on most Linux distributions and macOS. Windows users can install WSL (Windows Subsystem for Linux) or use Git Bash.

**How do I run a Bash script from anywhere?**

Place the script in a directory listed in your PATH environment variable (like /usr/local/bin), or call it with the full path. Ensure it has execute permissions.

**What does the shebang (#!) do?**

The shebang tells the system which program to use to interpret the script. For Bash, it is `#!/bin/bash`. Without it, the script may run under a different shell.

**Can I use Bash scripts on Windows?**

Yes, using Windows Subsystem for Linux (WSL), Cygwin, or Git Bash. The scripts run in a Unix-like environment on top of Windows.

**Why does my script work in the terminal but not from cron?**

Cron runs with a minimal environment. Your script might rely on PATH or shell variables not set in cron. Use full paths for all commands and set PATH at the start of the script.

**Is Bash the same as the shell?**

Bash is a specific shell program. Other shells include Zsh, Ksh, and Fish. The term 'shell' refers to any command-line interpreter.

## Summary

A Bash script is a plain text file containing a series of commands for the Bash shell, used to automate tasks on Unix-like operating systems. It is a fundamental tool for system administration, enabling efficiency, consistency, and reliability in managing servers, files, user accounts, and applications. Understanding Bash scripting involves learning syntax for variables, conditionals, loops, functions, and command substitution, as well as best practices like error handling, quoting, and using full paths.

For IT certification candidates, Bash scripting is a core objective in exams like CompTIA Linux+, RHCSA, and LPIC-1. Questions range from interpreting script output to writing small scripts during performance-based tests. Mastery of Bash scripting shows that you can think logically, troubleshoot effectively, and automate solutions, skills that are highly valued in the IT industry.

In the real world, Bash scripts are the backbone of countless automation tasks: from simple backups to complex multi-server deployments. They save time, reduce human error, and allow teams to manage infrastructure at scale. Whether you are a junior admin or a DevOps engineer, investing time in Bash scripting will pay dividends throughout your career. For the exam, focus on understanding common pitfalls like missing shebangs, improper syntax, and the difference between `sh` and `bash`, and practice writing scripts for common scenarios.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/bash-script
