Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

extract hostname with parameter expansion in a single assignment

I am trying to get the hostname for a url. I am able to do it with 2 assignments but I want to do it in a single step.

#!/usr/bin/env sh

HELM_CHART=oci://foo.bar.io/ns/chart-name

host=${HELM_CHART#*//}
host=${host%%/*}

echo "$host"
# foo.bar.io

I am not able to figure out a pattern or combination of pattern to achieve this. I read that you can combine a pattern like shown here Remove a fixed prefix/suffix from a string in Bash. I try all sorts of combinations, but I can’t get it working.

Is it possible to do in a single assignment?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t do this with parameter expansion alone. You can with a regular expression match, though. In bash,

[[ $HELM_CHART =~ ://([^/]*)/ ]] && host=${BASH_REMATCH[1]}

In POSIX shell,

host=$(expr "$HELM_CHART" :  '.*://\([^/]*\)/')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading