7

I'm working on a script to make setting up a Statamic site more efficient. The problem I'm running into is that the variable I'm using to replace a string in a file has unescaped forward slashes and is user input. How can I make sure that _site_url: http://statamic.com will become _site_url: http://example.com?

The code below will work as long as there are no forward slashes present.

echo "What's your site URL? Don't forget the protocol (ex. http://)!"
read -e SITE_URL

echo "%s/_site_url: http:\/\/statamic.com/_site_url: $SITE_URL/g
w
q
" | ex _config/settings.yaml
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Curtis Blackwell
  • 3,130
  • 3
  • 27
  • 45

2 Answers2

9

Since you specifically mentioned bash instead of Bourne shell or generic Unix shell, I'd recommend using Bash's built in search/replace feature:

echo "What's your site URL? Don't forget the protocol (ex. http://)!"
read -e SITE_URL

echo Escaped URL: ${SITE_URL//\//\\\/}
Christopher Smith
  • 5,372
  • 1
  • 34
  • 18
3

The problem is the delimiter in your ex command. We can put anything we'd like instead, I use @ here :

Try doing this :

 sed -i "s@_site_url: http://statamic.com/_site_url: $SITE_URL@g" _config/settings.yaml

Or with your ex command :

echo "What's your site URL? Don't forget the protocol (ex. http://)!"
read -e SITE_URL

echo "%s@_site_url: http://statamic.com@_site_url: $SITE_URL@g
w
q
" | ex _config/settings.yaml
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223