Skip to main content

CLI command

shell-command.sh is a template for a single-file Bash command-line interface (CLI) script. It needs only Bash and standard tools such as curl. This page is for developers who build their own command from the template in a project generated from Scaffold. Follow it to turn the template into your command.

By default, install.sh renames the script after your project, such as acme-app.sh. To pick another name, answer the Shell command name prompt, or pass --shell-command-name=NAME. On this page, use your script's name in place of shell-command.sh.

Template features​

The template provides the following:

  • Strict mode: set -euo pipefail stops the script at a failed command, an unset variable or a failed pipe.
  • Debug mode: Set the SCRIPT_DEBUG environment variable to 1 to print each command as it runs.
  • Prompts: ask reads a value, with an optional default. ask_yesno reads a y or n answer, with Y as its default, and returns it in lowercase.
  • Confirmation: The script asks Proceed? before it does its work. To continue, press Enter or answer y or Y. Any other answer, yes included, exits the script. To skip the question, set the SHOULD_PROCEED environment variable to y.
  • main function: The script's logic lives in main, which runs only when you run the script directly. Sourcing the script from another script loads its functions without running main.

The example logic takes the number of sides on a die as its first argument, or asks for it with 6 as the default. It exits with an error unless the number is a whole number from 2 to 100. It then rolls the die with Bash's $RANDOM and prints the result.

Adapt the script​

To turn the template into your own command:

  1. Update the description and the @usage lines in the comment block at the top of the script.

  2. Replace the sides="${1-}" line with code that reads the arguments your command takes.

  3. Replace the example logic in main with your own, including the validation of your arguments.

  4. Run the script from your project root:

    ./shell-command.sh

    Confirm that the script runs your logic. For comparison, the unchanged template prints Follow the prompts and asks for the number of sides.

Test the script​

tests/bats/shell-command.bats holds example tests for the template. After you adapt the script, update those tests to match its arguments and output. See Write tests.