A bash script is a text file of commands run in order. Start the file with #!/bin/bash, make it executable with chmod +x, then run it with ./script.sh.
Variables and input
- name="Ana" sets a variable (no spaces around =)
- echo "Hello $name" prints it
- read answer waits for the user to type
- $1, $2 are the script arguments
Conditions and loops
- if [ "$x" -gt 10 ]; then ... fi tests a number
- [ -f file ] is true when the file exists
- for f in *.txt; do ... done loops over files
- while [ "$n" -lt 5 ]; do ... done repeats
Functions and exit codes
- name() { ... } defines a function
- exit 0 ends the script successfully
- $? holds the exit code of the last command
- && runs the next command only if the last one succeeded