Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I escape forward slashes in a user input variable in bash?

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
like image 248
Curtis Blackwell Avatar asked Oct 19 '12 00:10

Curtis Blackwell


People also ask

How do you escape a forward slash in Bash?

A non-quoted backslash, \, is used as an escape character in Bash.

How do you escape special characters in variable Bash?

Bash Character Escaping. Except within single quotes, characters with special meanings in Bash have to be escaped to preserve their literal values. In practice, this is mainly done with the escape character \ <backslash>.

How do you escape a shell variable?

Escaping is a method of quoting single characters. The escape (\) preceding a character tells the shell to interpret that character literally. With certain commands and utilities, such as echo and sed, escaping a character may have the opposite effect - it can toggle on a special meaning for that character.

What does forward slash do in Bash?

Answer. The forward slash (/) and backslash (\) is referred to as a pathname separator. Either slashes (/) or backslashes (\) can be used as pathname separators in pathname patterns and version selectors, unless the config spec will be shared between UNIX (or Linux) and Windows hosts.


2 Answers

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//\//\\\/}
like image 140
Christopher Smith Avatar answered Nov 14 '22 21:11

Christopher Smith


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
like image 45
Gilles Quenot Avatar answered Nov 14 '22 22:11

Gilles Quenot