2
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?

Markus Weigelt
  • 352
  • 1
  • 3
  • 6

2 Answers2

1

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

One option is:

[[ $url == *:* ]] && port=${url#*:} || port=8080
pjh
  • 6,388
  • 2
  • 16
  • 17