Allowing scripts to run without user input

If your script requires user data during its run in order to make decisions on what to do, it can be tempting to prompt the user for each required bit of information when needed, perhaps using the -p option to the read builtin to request a prompt:

#!/bin/bash
read -p 'Do you want to create the directory? [y/N]: ' createdir
case $createdir in
    y*|Y*)
        mkdir -- "$HOME"/myscript || exit
        ;;
esac

This example will only create the directory named in the dir variable if a string such as y or YES (or yoyo!) is read from standard input, and assumes that it is likely to be the user's terminal.

This is convenient for interactive scripts, but it assumes that the user running the script is actually at a terminal, ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.