Bash
A command shell and scripting language used to automate tasks on Linux and Unix-like systems.
Why it exists.
It makes repeatable command-line operations composable and easy to run in automation.
Where it shines.
System tasks, CI jobs, local tooling, and glue code around command-line programs.
Where not to use it.
Do not use complex Bash as a replacement for a maintainable application or typed automation tool.
What it is made of.
- Commands
- Pipes
- Variables
- Functions
- Exit codes
How it works.
- A script invokes commands
- Pipes connect their output
- Exit codes signal success or failure
- Automation reacts to the result
How it works
From text to commands
Bash reads commands, expands variables and substitutions, applies redirection, then executes builtins or external programs found through PATH. Commands return an exit status: 0 means success; nonzero means failure.
printf "Hello from Bash\n"
printf "Last status: %s\n" "$?"Run your first script
Save as hello.sh. The shebang selects Bash when you execute the file directly. bash hello.sh requires read access; ./hello.sh also requires execute permission. Running a script creates a separate shell; source hello.sh executes in the current shell.
#!/usr/bin/env bash
name="World"
printf "Hello, %s!\n" "$name"Run and check
bash -n checks syntax without running the script. bash -x traces execution; avoid tracing scripts that handle secrets.
bash -n hello.sh
bash hello.sh
chmod +x hello.sh
./hello.shVariables & print
Assign, expand, and quote
Assignments have no spaces around =. Double quotes allow expansion and preserve spaces. Single quotes keep text literal. export makes a variable available to child processes.
name="Ada Lovelace"
printf "Hello, %s\n" "$name"
printf '%s\n' 'Literal: $name'
export APP_ENV="development"Print output
echo is convenient for simple messages. printf uses a fixed format and gives predictable formatting; pass variable data as arguments.
echo "Starting script"
message="Build complete"
printf '%s\n' "$message"
printf 'Count: %d\n' 3Arguments and input
$1 is the first argument; "$@" preserves all arguments individually. ${1:-World} supplies a default. read -r keeps backslashes literal.
name="${1:-World}"
printf 'Hello, %s\n' "$name"
read -r -p "Your environment: " environment
printf 'Selected: %s\n' "$environment"If / else
Branch on a condition
An if block ends with fi. [[ ... ]] tests strings or files; (( ... )) evaluates arithmetic. elif adds another branch. In Bash, the condition succeeds when its command returns 0.
count=3
if (( count > 5 )); then
printf 'Large batch\n'
elif (( count > 0 )); then
printf 'Small batch\n'
else
printf 'Nothing to process\n'
fiStrings and files
-n tests a nonempty string, -z tests an empty string, -f checks for a regular file, and -d checks for a directory. Spaces around [[ and ]] are required.
environment="production"
if [[ "$environment" == "production" ]]; then
printf 'Production selected\n'
fi
if [[ -f "config.json" ]]; then
printf 'Config exists\n'
else
printf 'Config missing\n'
fiCheck a command directly
Use the command itself as the condition rather than inspecting $? later, after another command may have changed it.
if command -v curl >/dev/null 2>&1; then
printf 'curl is available\n'
else
printf 'Install curl first\n' >&2
exit 1
fiFor loops
Iterate over a list
for assigns each item to a variable and runs the block. done closes the loop. Quote expansions to preserve each item.
for environment in development staging production; do
printf 'Environment: %s\n' "$environment"
doneCount with arithmetic
The arithmetic form defines initialization, condition, and increment. break exits a loop; continue moves to its next iteration.
for (( i=1; i<=3; i++ )); do
printf 'Attempt %d\n' "$i"
doneIterate over files safely
Use globs instead of parsing ls output. The file check skips an unmatched pattern when no .log files exist.
for file in ./*.log; do
[[ -f "$file" ]] || continue
printf 'Log: %s\n' "$file"
doneAPI calls
GET a JSON response
curl sends HTTP requests; Bash coordinates the call. This example reads a public GitHub endpoint. -sS hides progress but shows errors; --fail returns a nonzero status for HTTP errors; --max-time bounds the request.
if response=$(curl --fail --silent --show-error --max-time 20 \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/octocat/Hello-World"); then
printf '%s\n' "$response"
else
printf 'API request failed\n' >&2
exit 1
fiRead JSON with jq
Install jq to parse JSON. Run after the successful GET above. jq -r prints a string without JSON quotes; Bash does not parse JSON itself.
printf '%s\n' "$response" | jq -r '.full_name'POST JSON with authentication
Replace the example endpoint and supply API_TOKEN through your environment. Save the request JSON as payload.json. --data-binary selects POST and sends the file; -H adds headers. Avoid logging tokens.
: "${API_TOKEN:?Set API_TOKEN first}"
curl --fail --silent --show-error --max-time 20 \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @payload.json \
"https://api.example.com/items"