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