0

I want to take a bash script param with forward slash like this my_server/my_repo/my_image and pass them into a sed function that does a replace on the string and rewrites for a different file.

I'm able to do this by escaping the forward slashes when setting the string, like this:

#!/usr/bin/bash

IMAGE_NAME="my_server\/my_repo\/my_image"
CURRENT_VERSION="1.0.0"
TARGET_VERSION="1.0.1"
TARGET_FILE="./my_deployment.yaml"

sed -i "s/$IMAGE_NAME:$CURRENT_VERSION/$IMAGE_NAME:TARGET_VERSION/" "$TARGET_FILE"

That's great, but when I pass the same string, escaped or unescaped, I can't get it to work. I'm pretty sure it is because the variable $IMAGE_NAME is unescaping the / while in the sed command, which completely throws off sed when doing the replacement.

I've tried various combindations escaping the argument and unescaping:

> ./myscript.sh my_server/my_repo/my_image
> ./myscript.sh my_server\/my_repo\/my_image

Tranforming argument when assigning it to $IMAGE_NAME and other varios combindations.

> IMAGE_NAME=$1
> IMAGE_NAME="$1"
> IMAGE_NAME=`echo $1 | sed 's/\//\\\//g'`

I'm sure it is something to do with how bash does strings and escaping but I can't figure how.

So, How do I get the string that is passed like this as an argument:

my_server/my_repo/my_image

Output this when being called from a variable:

my_server\/my_repo\/my_image    
1

You need to protect the backslashes from the shell on the command line either by using quotes OR double them up.

myscript.sh 
'my_server\/my_repo\/my_image'
..... Or
myscript.sh my_server\\/my_repo\\/my_image
1
  • Thank you! I spent a few hours on this.... thank you so much! – DogEatDog May 3 at 23:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.