Languages
[Edit]
EN

Bash - read variable with default value

6 points
Created by:
Maryamcc
511

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}"

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Bash

Bash - read variable with default value
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join