Home > database >  Set default value after parameter substitution with remove pattern
Set default value after parameter substitution with remove pattern

Time:06-29

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?

CodePudding user response:

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

CodePudding user response:

One option is:

[[ $url == *:* ]] && port=${url#*:} || port=8080
  • Related