Read Variable Default Values into Bash

When using read to get a value from the user, it’s really nice to have a default that they can just hit enter to.

To do this, you can use parameter expansion:

read -p "Enter an animal: " animal
animal=${animal:-Tiger}
echo $animal

The animal=${animal:-Tiger} says only set amimal to Tiger if `amimal is not already set.

You can also have it set before:

animal=Tiger
echo "Right now I have $animal"
read -p "Enter a different animal if you wish (or hit Enter to keep it as $animal): " animal_entered
anmal=${animal_entered:-$animal}
echo $animal