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:
xxxxxxxxxx
1
2
3
read username
4
username=${username:-admin}
5
6
echo "Used username: ${username}"
Where: admin
word should be changed to desired value.
or with message:
xxxxxxxxxx
1
2
3
read -p "Username [admin]: " username
4
username=${username:-admin}
5
6
echo "Used username: ${username}"
This section shows how to store default value in variable.
xxxxxxxxxx
1
2
3
default_username=Admin
4
5
read -p "Username [${default_username}]: " typed_username
6
typed_username=${typed_username:-${default_username}}
7
8
echo "Used username: ${typed_username}"
In this section we want to show how to assign default value with test
command.
xxxxxxxxxx
1
2
3
read username
4
test -z "${username}" && username=admin
5
6
echo "Used username: ${username}"