DEV Community

Cover image for Shell features you didn't know you needed (or possibly even existed) #9
Mike Whitaker
Mike Whitaker

Posted on

Shell features you didn't know you needed (or possibly even existed) #9

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 \/ \-)
Enter fullscreen mode Exit fullscreen mode
  • using sed
IMAGE_TAG=$(echo $BRANCH | sed -e 's/\//-/g')
Enter fullscreen mode Exit fullscreen mode
  • using perl
IMAGE_TAG=$(echo $BRANCH | perl -pe 's/\//-/g')
Enter fullscreen mode Exit fullscreen mode

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//\//-}
Enter fullscreen mode Exit fullscreen mode

To clarify, that's essentially:

${VARIABLE/from/to} # replace first occurrence of 'from' 
${VARIABLE//from/to} # replace all occurrences of 'from'
Enter fullscreen mode Exit fullscreen mode

Simple, when you know how.

Top comments (0)