使用“read”读取变量并保留用户输入的反斜杠

bin*_*nzq 3 shell read

我正在使用read这样从用户读取路径:

read -p "Input the file name: " FilePath
Run Code Online (Sandbox Code Playgroud)

用户现在输入此字符串:

\Supernova\projects\ui\nebula
Run Code Online (Sandbox Code Playgroud)

我能做些什么来代替\/。我想要的结果是:

/Supernova/projects/ui/nebula 
Run Code Online (Sandbox Code Playgroud)

顺便说一句,命令:

echo $FilePath
Run Code Online (Sandbox Code Playgroud)

输出结果:

Supernovaprojectsuinebula
Run Code Online (Sandbox Code Playgroud)

我不知道有什么问题。

Jos*_* R. 8

问题是read将尝试评估用户输入的反斜杠转义。要执行您想要的操作,您需要添加告诉它不评估反斜杠转义的-r开关read

read -rp "Input file name: " FilePath
UnixPath="${FilePath//\\//}"
Run Code Online (Sandbox Code Playgroud)

此外,您的echo命令需要在变量替换周围使用双引号echo "$FilePath"