Languages
[Edit]
EN

Bash - read variable with default value

6 points
Created by:
AnnLen
12430

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

 

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