Set default value after parameter substitution with remove pattern

Viewed 42
URL=example.com
#URL=example.com:8080

PORT=${URL#*:}
PORT=${PORT:-8080}

I want to do the parameter substitution with remove pattern and the default in one line.

Is the a way to set default when parameter substitution is empty?

2 Answers

For doing this in a one step in bash, you can use read with IFS=: with a default value appended to url variable like this:

url='example.com:7000'

IFS=: read host port _ <<< "$url:8080"

# check host and port values
declare -p host port
echo '------'

url='example.com'

IFS=: read host port _ <<< "$url:8080"

# check host and port values
declare -p host port

Output:

declare -- host="example.com"
declare -- port="7000"
------
declare -- host="example.com"
declare -- port="8080"

Online Code Demo

Related