Substituting the contents of a variable in Bash.
I came across this one needing to turn a Git branch name into a Docker image tag, and having it trip over the fact that our branch naming convention is <user>/<issue>/<short description>, and Docker doesn't like / in tags.
Obviously there are many ways of stripping/substituting the /: for example,
- using
tr
IMAGE_TAG=$(echo $BRANCH | tr \/ \-)
- using
sed
IMAGE_TAG=$(echo $BRANCH | sed -e 's/\//-/g')
- using
perl
IMAGE_TAG=$(echo $BRANCH | perl -pe 's/\//-/g')
And there's probably others with awk, and who knows what else.
But why bother, when you can do it in bash itself.
IMAGE_TAG=${BRANCH//\//-}
To clarify, that's essentially:
${VARIABLE/from/to} # replace first occurrence of 'from'
${VARIABLE//from/to} # replace all occurrences of 'from'
Simple, when you know how.
Top comments (0)