Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Unix shell script is a text file of commands that a shell reads and executes. It lets you reuse commands and combine system utilities to automate routine work. This guide uses Bash for its examples and explains where syntax differs if you need a portable POSIX-style sh script.

What a shell does

A shell is both a command interpreter and a programming language. At a terminal, it reads commands and runs programs; in a script, it combines commands with variables, conditions, loops, functions, and input/output rules. The GNU Bash Reference Manual, Edition 5.3, updated May 18, 2025, describes these roles and the parts of shell programming: Bash Reference Manual.

A script is a file containing commands for the shell to read. Instead of retyping a routine sequence, you can save it, make it executable, and run it again. The shell also handles text before a program receives it: it recognizes syntax, expands variables and patterns, applies redirections, then executes commands. Understanding that order explains many beginner surprises.

Write and run your first Bash script

Create a file named hello.sh with this content:

#!/usr/bin/env bash
printf 'Hello, %s!n' "${1:-world}"

The first line is the shebang: it asks the operating system to run the file with Bash found through /usr/bin/env. The second line prints the first argument, or world if none was supplied. Save the file, then run it explicitly with Bash:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
bash hello.sh
bash hello.sh Ada

Alternatively, make it executable and invoke it by path:

chmod +x hello.sh
./hello.sh Ada

Use ./ to run a script in the current directory; the current directory is not necessarily searched when you type only a filename. The shebang’s interpreter must exist on the target system. Running bash hello.sh explicitly avoids relying on executable permissions or the shebang, but still requires Bash.

Commands, arguments, and shell parsing

A command is commonly a program name followed by arguments. For example, printf '%sn' 'two words' runs printf with a format argument and one data argument. The shell does not simply pass each line untouched to a program: it reads input, recognizes words and operators under quoting rules, parses commands, performs expansions, applies redirections, and executes. The program receives the resulting arguments, not the original line of text.

Whitespace usually separates words. Thus printf '%sn' two words passes two data arguments, whereas quoting 'two words' keeps that phrase as one argument. Characters such as *, $, |, and > have special shell meanings in relevant contexts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quoting: keep data from becoming syntax

Quoting controls which characters the shell treats specially. Single quotes preserve their contents literally, while double quotes preserve most characters but still allow selected expansions such as variables and command substitutions. The Bash manual explains quoting in detail: Quoting.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
  • '$HOME *.txt' is literal text: neither the variable nor the wildcard expands.
  • "$HOME" expands the variable, but keeps its result as one word, even if it contains spaces.
  • "*.txt" keeps the asterisk literal rather than matching filenames.

Quote variable expansions by default, especially when passing filenames or user-provided text to commands. For example:

name='Ada Lovelace'
printf 'User: %sn' "$name"

Without quotes, an expansion can be split into multiple words and wildcard characters in its result can expand against filenames. Use unquoted expansions only when you deliberately need the shell’s splitting or pattern matching behavior.

Variables, parameters, and expansions

Assign a variable with no spaces around the equals sign. Refer to its value with a dollar sign:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
output_file='report.txt'
printf 'Writing to %sn' "$output_file"

Spaces around = would make the line a command and its arguments rather than an assignment. Positional parameters provide the script’s arguments: $1 is the first, $2 the second, and $# their count. Prefer "$@" to pass all arguments on individually while preserving spaces:

printf 'Argument: %sn' "$@"

Bash’s ${name:-default} expansion supplies a default when a parameter is unset or empty, as in the first example. Bash also offers other parameter expansions; mark Bash-specific syntax when portability matters.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Exit status and handling failures

Each command returns an exit status: conventionally, zero means success and a nonzero value indicates an error or another unsuccessful result. The special parameter $? contains the most recent command’s status, so inspect it immediately if needed:

cp source.txt backup.txt
status=$?
if [ "$status" -ne 0 ]; then
  printf 'Copy failed (status %s)n' "$status" >&2
  exit "$status"
fi

Often it is clearer to put a command directly in an if condition:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if cp source.txt backup.txt; then
  printf 'Copy completen'
else
  printf 'Copy failedn' >&2
  exit 1
fi

Do not assume a script succeeded merely because it printed output. Check the status when later steps depend on a command working. Bash has options such as set -e, but its behavior has exceptions and context-dependent details; explicit checks make failure handling easier to understand.

Conditions and loops

Use if to choose actions based on command success or a test. This Bash example checks whether a path names a regular file:

file='report.txt'
if [ -f "$file" ]; then
  printf 'Found %sn' "$file"
else
  printf 'Missing %sn' "$file" >&2
fi

Quote the path expansion so a filename with spaces remains a single test argument. For a basic repeat over arguments, a for loop is useful:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
for file in "$@"; do
  printf 'Received: %sn' "$file"
done

A while loop repeats while its condition succeeds. Shell loop syntax is concise, but be careful with data from files: reading lines with read has details around backslashes and whitespace that require deliberate options when preserving arbitrary input.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Functions for reusable steps

Functions let you give a command sequence a name. In Bash:

say_hello() {
  printf 'Hello, %s!n' "${1:-world}"
}

say_hello Ada

Function arguments use the same positional parameters, such as $1. A function’s exit status is usually the status of its last command unless you explicitly return another status. Keep functions focused and quote their parameter expansions as you would in the top-level script.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Redirection and pipelines

Redirection connects a command’s input or output to a file or another destination. For example, command >out.txt writes standard output to a file, replacing its previous contents; command >>out.txt appends instead. Standard error can be redirected separately with 2>errors.txt. A pipeline sends one command’s standard output to the next command’s standard input:

printf '%sn' *.txt | sort

This prints the shell-expanded matching filenames in sorted order. Redirection order matters; pipeline exit-status behavior can also depend on the shell. Bash offers set -o pipefail so a pipeline can report failure from a command before the last one, but that option is not POSIX shell syntax.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Choose Bash or portable sh deliberately

Write for the shell named by the script’s shebang and required by the target environment. POSIX specifies important shell behavior, including pipelines, redirection, quoting, argument handling, variable expansion, and flow control. Bash aims to implement the POSIX Shell and Tools specification, but its default behavior is not identical to POSIX in every area; Bash’s POSIX mode narrows some differences. See the manual’s Bash POSIX mode discussion.

Choice When it fits Portability consideration
#!/bin/sh When the script should use POSIX shell constructs and the system’s sh. Do not use Bash-only syntax; sh may be another shell.
#!/usr/bin/env bash When Bash is required and available through the user’s command search path. Bash-specific constructs are not guaranteed in sh or other shells.

For a script intended for multiple Unix-like systems, keep syntax within the POSIX shell language and verify the target’s available utilities too; shell portability does not make every external command identical across systems. For a Bash-only script, say so and use Bash consistently rather than relying on whichever shell happens to launch it.

Common beginner problems and fixes

  • “Command not found” for the script: invoke a file in the current directory as ./script.sh, or provide its full path. Check that its interpreter exists.
  • Permission denied: run chmod +x script.sh before direct execution, or run bash script.sh if Bash is the intended interpreter.
  • Arguments split unexpectedly: quote expansions such as "$name"; use "$@" when forwarding all arguments separately.
  • Wildcard stayed literal: check whether it was quoted. A quoted "*.txt" is data, not a filename pattern.
  • Assignment appears to run as a command: write name='value' without spaces around the equals sign.
  • A later command runs after an earlier failure: test the earlier command’s status and choose explicitly whether to report, recover, or stop.
  • Script works in Bash but not with sh: check the shebang and remove Bash-only syntax, or run it with Bash as intended.

Or skip the browser setup

If your shell task is to capture a website screenshot, ScreenshotNeo offers a one-request alternative to setting up a browser. It accepts a URL and returns an image or PDF; its cookie-banner, popup, and chat-widget removal can be turned off when not wanted. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status. It also has an MCP server for AI agents.

Use the API key from your ScreenshotNeo account; the API documentation is at ScreenshotNeo docs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo offers 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo or sign up for the free plan.

Frequently Asked Questions

Does a shell script need a .sh extension?

No. The extension is a naming convention; execution depends on how you invoke the file, its contents, permissions, and interpreter.

Can I run a Bash script on every Unix-like system?

Only where Bash is available and the script’s assumptions are supported. For broader compatibility, target POSIX shell syntax and the utilities available on your target systems.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.