Skip to content
Lab 3 of 4

A Script Others Can Use: Arguments, Options & Exit Codes

Every morning Harpreet asks which items are running low at a store. Turn the answer into lowstock: a command with a positional argument, a -t option, clean data on stdout, errors on stderr and exit codes another script can act on.
  • Intermediate
  • 44 min
  • Bash
  • Scripting
  • CLI design
  • Kestrel

Overview

Every morning Harpreet Kaur, head of operations, messages Simran: "What's running low at store 3?" Simran runs a curl and a jq, pastes the result, and loses ten minutes. Today that becomes a command anyone can run:

lowstock [-t THRESHOLD] STORE_ID

A one-off command line becomes a tool when other people — and other scripts — can rely on it: it takes arguments and options the standard way, prints only data on stdout so it can be piped, sends complaints to stderr, and tells its caller what happened with an exit status. You will build lowstock step by step against Kestrel's real API, and finish by using it the way Unix tools are meant to be used: inside a pipeline, over every store at once.

What you will learn

  • Write an executable script in ~/bin that takes a positional argument
  • Parse options with getopts and validate their values
  • Keep stdout for data and send errors and usage to stderr
  • Define and return meaningful exit codes: 0, 2 for usage, 3 for not found
  • Compose your script with other tools using xargs

Before you start

  • Bash That Fails Loudly first, or comfort with set -euo pipefail
  • You have used curl; jq is introduced as you go

Tasks

  1. 01A first version: one positional argument
  2. 02Options with getopts
  3. 03Exit codes a caller can act on
  4. 04Use it like a Unix tool

Next in this course