Skip to content
Justice Tech School

Bash Tutorial

Automate tasks with shell scripts on Linux and macOS.

Start learning Bash
Getting started4 lessons
  1. 1Bash IntroductionAutomate the command line.
  2. 2Running ScriptsSave commands in a file, start it with a shebang line such as #!/bin/bash, make it executa.
  3. 3Shell BasicsThe shell runs commands.
  4. 4Comments and echo# starts a comment.
Basics30 lessons
  1. 5VariablesAssignment with no spaces.
  2. 6Conditionsif and test.
  3. 7Loopsfor, while and ranges.
  4. 8QuotingDouble quotes allow $variable expansion, single quotes keep everything literal, and a back.
  5. 9Special Variables$0 is the script name, $1 to $9 are arguments, $# counts them, $@ lists them, $? is the la.
  6. 10Parameter Expansion${var:-default} gives a default, ${var#prefix} and ${var%suffix} trim text, ${var/old/new}.
  7. 11ArithmeticUse $(( )) for integer math: + - * / % and **.
  8. 12Reading Inputread stores a line into a variable.
  9. 13Exit Status and ChainingEvery command returns 0 for success or non zero for failure.
  10. 14echo and printfecho prints text and printf formats it.
  11. 15VariablesAssign with name=value and no spaces around =.
  12. 16QuotingDouble quotes allow variables, single quotes are literal and backslash escapes one charact.
  13. 17Command Substitution$(command) runs a command and inserts its output.
  14. 18ArithmeticUse $(( )) for integer maths.
  15. 19String Length and Slices${#var} gives the length and ${var:start:len} slices.
  16. 20Default Values${var:-default} uses a default, ${var:=default} also assigns it and ${var:?msg} fails if u.
  17. 21Replace and Trim in Variables${var/old/new} replaces, ${var#pat} removes a prefix and ${var%pat} removes a suffix.
  18. 22Upper and Lower Case${var^^} makes upper case and ${var,,} makes lower case.
  19. 23Reading Inputread stores a line in a variable.
  20. 24Exit CodesEvery command returns a number.
  21. 25Comments and the ShebangA line starting with # is a comment.
  22. 26Sequences with seq and bracesseq prints numbers and braces make lists and ranges.
  23. 27Formatting Datesdate +FORMAT prints parts of a date.
  24. 28Comparing NumbersUse -eq -ne -lt -le -gt -ge inside [[ ]] or the operators inside (( )).
  25. 29&& and || Chainingcmd1 && cmd2 runs the second only on success.
  26. 30Printing Tables with printfprintf with widths aligns columns.
  27. 31Array Slices and Lengths${a[@]:start:count} slices an array and ${#a[@]} counts items.
  28. 32Sorting and Comparing StringsInside [[ ]] use < and > for alphabetical order and == for equality, with quotes.
  29. 33Subshells( ) runs commands in a child shell.
  30. 34Getting HelpUse man for manuals, command --help for quick usage and type or which to find where a comm.
Text and strings10 lessons
  1. 35String OperationsBash offers substring ${s:start:len}, length ${#s}, case change ${s^^} and ${s,,}, and pat.
  2. 36Here Documents and Here Strings<<EOF feeds several lines to a command.
  3. 37Wildcards and Brace Expansion* matches any text, ? one character and [abc] a set.
  4. 38Here Documents and Here Strings<<EOF feeds multi line text to a command and <<< feeds a string.
  5. 39tr, cut and pastetr translates characters, cut selects fields and paste joins lines.
  6. 40sort and uniqsort orders lines.
  7. 41grep Patternsgrep prints matching lines.
  8. 42sed Basicssed edits streams.
  9. 43awk Basicsawk splits lines into fields $1, $2.
  10. 44wc, head and tailwc counts lines, words and bytes.
Control flow12 lessons
  1. 45Test OperatorsInside [[ ]] use -eq -ne -gt -lt for numbers, == != for strings, -z for empty and -n for n.
  2. 46Case Statementscase matches a value against patterns, each ending with ;;.
  3. 47More Loopsfor iterates words, ranges and files.
  4. 48select Menusselect builds a numbered menu and loops until break.
  5. 49if, elif and elseRun commands by condition.
  6. 50Testing Strings and NumbersStrings use == != -z -n.
  7. 51Testing Files-e exists, -f regular file, -d directory, -r readable, -s not empty.
  8. 52case Statementscase matches a value against patterns.
  9. 53for LoopsLoop over words, ranges, globs or C style counters.
  10. 54while, until and breakwhile repeats while a command succeeds.
  11. 55Reading Files Line by Linewhile read loops over lines.
  12. 56select Menusselect builds a numbered menu from a list.
Arrays and functions11 lessons
  1. 57Indexed ArraysArrays hold many values.
  2. 58Associative Arraysdeclare -A creates a map from keys to values.
  3. 59Functions In DepthFunctions take arguments as $1 $2 and $@.
  4. 60Scope and RecursionVariables are global unless declared local.
  5. 61ArraysBash has indexed arrays.
  6. 62Associative Arraysdeclare -A creates a key value array.
  7. 63FunctionsDefine with name() { }.
  8. 64local Variableslocal limits a variable to the function.
  9. 65Return Values and Statusreturn gives an exit status 0 to 255.
  10. 66Script Arguments$1 to $9 are arguments, $# counts them, $@ lists them and shift removes the first.
  11. 67Defaults and ValidationCheck argument counts and give defaults with ${1:-value}.
Scripting7 lessons
  1. 68Arrays and FunctionsReusable pieces.
  2. 69Pipes and Text ToolsChain commands.
  3. 70Script Arguments and getoptsScripts read arguments with $1 and $@.
  4. 71Strict Mode and Safetyset -e exits on errors, set -u fails on unset variables and set -o pipefail catches failur.
  5. 72Traps and Signalstrap runs a command when the script exits or receives a signal such as INT or TERM.
  6. 73Subshells and Command Substitution$( ) captures a command output.
  7. 74Debugging ScriptsRun with bash -x to trace each command, add set -x around a section, and use shellcheck to.
Files and processes19 lessons
  1. 75Working with Filestouch creates, cp copies, mv renames, rm deletes, ln links, find searches, stat shows deta.
  2. 76Redirection> writes, >> appends, < reads, 2> redirects errors, &> sends both and 2>&1 merges errors i.
  3. 77Pipes and PipelinesA pipe connects one command output to another input.
  4. 78Processes and Jobscommand & runs in the background, jobs lists them, wait waits, kill sends a signal, $! is .
  5. 79Environment Variablesexport makes a variable visible to child programs.
  6. 80PermissionsFiles have read, write and execute rights for owner, group and others.
  7. 81Files and Directoriesmkdir, cp, mv, rm, touch and ls manage files.
  8. 82Redirection> writes, >> appends, < reads, 2> redirects errors and &> redirects both.
  9. 83Pipes and teeA pipe sends output to the next command.
  10. 84findfind searches directories by name, type, size and time.
  11. 85xargsxargs turns input into arguments for a command.
  12. 86Globbing and Brace Expansion* matches any text, ? one character, [] a set and {a,b} lists alternatives.
  13. 87Environment Variablesexport makes a variable visible to child processes.
  14. 88Jobs and Processes& runs in the background, wait waits for it and $! is its pid.
  15. 89traptrap runs code on signals or when the script exits.
  16. 90Safer Scriptsset -euo pipefail stops on errors, unset variables and failed pipes.
  17. 91Practice: Backup NamesBuild file names from variables.
  18. 92Practice: Count WordsPipe text through standard tools.
  19. 93Practice: Simple Menu ScriptCombine functions, case and arguments.
Text processing6 lessons
  1. 94grep Searches Textgrep finds lines that match a pattern.
  2. 95sed Edits Textsed edits streams.
  3. 96awk Processes Columnsawk splits lines into fields $1 $2 and runs actions.
  4. 97sort, uniq, cut, tr, wcsort orders lines, uniq collapses neighbours, cut selects columns, tr translates character.
  5. 98find and xargsfind searches folders by name, type, size or age and can run commands on results.
  6. 99JSON and Web Requestscurl fetches URLs and jq filters JSON.
Advanced BashPremium5 lessons
  1. 100Process Substitution and Parallel Work<( ) lets commands that need files read output instead.
  2. 101Regular Expressions in Bash=~ matches ERE and fills BASH_REMATCH with groups.
  3. 102Parsing Arguments RobustlyFor long options write a while loop with case and shift.
  4. 103Error Handling PatternsCheck exit codes, send errors to stderr with >&2, use die helpers, retry flaky commands an.
  5. 104Performance TipsAvoid spawning processes in loops.
Bash in practicePremium6 lessons
  1. 105Project: Backup ScriptCombine what you learned: validate arguments, create a timestamped archive, report success.
  2. 106Project: Log AnalyserCount status codes, find the busiest pages and extract errors using grep, awk, sort and un.
  3. 107Cron and Schedulingcron runs commands on a schedule.
  4. 108Aliases, Functions and Dotfiles~/.bashrc runs for interactive shells.
  5. 109Shell SecurityQuote variables, validate input, never eval untrusted text, use mktemp, avoid secrets on t.
  6. 110Bash Best PracticesStart with a shebang, set -euo pipefail, quote variables, use functions, add usage text, p.
Next steps2 lessons
  1. 111What Next?Where to go after the basics.
  2. 112Practice ProjectsAutomate: a backup tool, a project scaffold generator, a log summariser, a deployment scri.