如何在bash中的用户输入变量中转义正斜杠?

Cur*_*ell 5 variables bash user-input escaping

我正在编写一个脚本,以便更有效地设置Statamic站点.我遇到的问题是我用来替换文件中的字符串的变量具有未转义的正斜杠并且是用户输入.我怎样才能确保_site_url: http://statamic.com会成为_site_url: http://example.com

只要没有正斜杠,下面的代码就会起作用.

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
Run Code Online (Sandbox Code Playgroud)

Chr*_*ith 7

由于您特别提到了 bash 而不是 Bourne shell 或通用 Unix shell,我建议使用 Bash 的内置搜索/替换功能:

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

echo Escaped URL: ${SITE_URL//\//\\\/}
Run Code Online (Sandbox Code Playgroud)


Gil*_*not 2

问题是你的ex命令中的分隔符。我们可以放置任何我们想要的东西,我@在这里使用:

尝试这样做:

 sed -i "s@_site_url: http://statamic.com/_site_url: $SITE_URL@g" _config/settings.yaml
Run Code Online (Sandbox Code Playgroud)

或者用你的ex命令:

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
Run Code Online (Sandbox Code Playgroud)