EN
Bash - read variable with default value
6
points
In this short article we would like to show how in Bash set default value for data read from terminal if data was not typed.
Quick solution:
#!/bin/bash
read username
username=${username:-admin}
echo "Used username: ${username}"
Where: admin
word should be changed to desired value.
or with message:
#!/bin/bash
read -p "Username [admin]: " username
username=${username:-admin}
echo "Used username: ${username}"
Default value from variable
This section shows how to store default value in variable.
#!/bin/bash
default_username=Admin
read -p "Username [${default_username}]: " typed_username
typed_username=${typed_username:-${default_username}}
echo "Used username: ${typed_username}"
Alternative solutions
In this section we want to show how to assign default value with test
command.
#!/bin/bash
read username
test -z "${username}" && username=admin
echo "Used username: ${username}"