【问题标题】:Back-slashes are disappearing from user input (read -p)反斜杠从用户输入中消失(读取 -p)
【发布时间】:2019-01-24 17:14:53
【问题描述】:

在我的脚本中,我要求用户指定路径。因为我在 Windows 上,所以我想将所有 \ 替换为 /。这将是一项简单的任务,但我遇到了一些麻烦:

read -p "Please, type/paste the working path (folder) you wish to link this scripts: " working_dir

我已经按照这个答案所说的做了:

https://stackoverflow.com/a/6853452/3286975

tr '\\' '/'

https://superuser.com/a/1068082/634144

home_mf="${home//\\//}"

https://stackoverflow.com/a/50220624/3286975

sed 's/\\/\//g'

但我没有运气。我就是这样做的:

working_dir=$(echo "$working_dir" | <some of the pipe I typed before>)
echo $working_dir

编辑:

所有引用的文本对问题没有用处。我以为问题出在这里。但是在read -pcommand 下回显$working_dir:

read -p "Please, type/paste the working path (folder) you wish to link this scripts: " working_dir
echo $working_dir

输出这个:

为什么反斜杠消失了?我的逻辑认为BG 也应该被转义,还是我错了?

【问题讨论】:

  • "${home//\\//}" 应该可以正常工作。 declare -p home 的输出是什么?
  • 而不是&lt;some of the pipe I typed before&gt;,如果不是太大,请准确显示您尝试过的内容以及setup.sh 的其余部分。该错误甚至看起来与您所质疑的操作没有任何关系,但很难说。
  • 天哪,@anubhava 我以为问题出在替换上。是在输入。我将编辑整个问题。
  • 例如,输入bash 提示符:x=\\a\\b\\c ; x=$(echo "$x" | tr '\\' '/'); echo $x 产生/a/b/c

标签: bash replace backslash


【解决方案1】:

您想使用read-r 开关不允许反斜杠转义任何字符(如help read 中所述)。

所以这会起作用:

read -rp "Please, type/paste the working path (folder) you wish to link this scripts: " working_dir
working_dir=${working_dir//\\//}

【讨论】:

  • 谢谢!这很有用。我不知道 read 命令上的 -r 参数。
  • 这应该是默认的!所以始终使用read-r 开关,除非你真的想让反斜杠成为转义字符!
  • 好的,我会处理的。
  • 还有一个潜在的复杂情况:echo 的某些版本会尝试解释转义符(反斜杠),因此即使它们正确位于变量中,也可能不会被打印。代替echo,使用printf '%s\n' "$working_dir"
猜你喜欢
  • 2011-12-31
  • 1970-01-01
  • 2014-09-20
  • 2020-08-24
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 2019-06-23
相关资源
最近更新 更多