Bash scripting uses shell commands to automate tasks, manage files, and run programs from the command line. This cheat sheet helps students remember the syntax patterns that appear again and again in scripts. It is useful for writing small automation tools, processing text files, and understanding how operating systems handle commands.
Clear examples make it easier to avoid common syntax errors.
Key Facts
- A Bash script usually starts with the shebang #!/bin/bash so the system knows to run the file with Bash.
- A variable is assigned with name=value and used with $name, with no spaces around the equals sign.
- Command-line arguments are read with 2, #.
- An if statement uses if [ condition ]; then commands; fi, and spaces are required inside the square brackets.
- A for loop can repeat through values using for item in list; do commands; done.
- A while loop repeats while a condition is true using while [ condition ]; do commands; done.
- Input and output redirection use > to overwrite a file, >> to append to a file, and < to read input from a file.
- A pipe sends the output of one command into another command using command1 | command2.
Vocabulary
- Shell
- A shell is a command interpreter that lets a user run programs and control the operating system.
- Bash
- Bash is a common Unix shell and scripting language used to run commands and automate tasks.
- Shebang
- A shebang is the first line of a script, such as #!/bin/bash, that tells the system which interpreter to use.
- Variable
- A variable is a named storage location that holds text, numbers, or command results for later use in a script.
- Pipe
- A pipe is the | operator that sends the output of one command as input to another command.
- Redirection
- Redirection changes where a command gets input from or sends output to, such as a file instead of the screen.
Common Mistakes to Avoid
- Writing spaces around variable assignment, such as count = 5, is wrong because Bash treats count as a command instead of creating a variable.
- Forgetting spaces in test brackets, such as [ $x -gt 5], is wrong because Bash requires spaces after [ and before ].
- Using > when you meant >> is wrong because > overwrites the file, while >> adds new output to the end of the file.
- Forgetting to quote variables, such as using name", can break scripts when the value contains spaces or special characters.
- Running a script without execute permission is wrong because the operating system may refuse to run it until chmod +x script.sh is used.
Practice Questions
- 1 Write a Bash command that creates a variable named score with the value 92, then prints The score is 92.
- 2 Write an if statement that prints Pass if a variable named grade is greater than or equal to 70.
- 3 Write a pipeline that counts how many lines in students.txt contain the word absent.
- 4 Explain why pipes and redirection are useful when building a script that processes a large text file.