传递空格文件夹时出现错误

传递空格文件夹时出现错误

代码: -

filesDirName="/C/Users/OM\\ SAI\\ RAM/HelloWorldSagar"
echo ${filesDirName}
echo "cd ${filesDirName}"
cd ${filesDirName}

bash 输出:-

$ ./files.sh
/C/Users/OM\ SAI\ RAM/HelloWorldSagar
cd /C/Users/OM\ SAI\ RAM/HelloWorldSagar
./files.sh: line 4: cd: too many arguments

答案1

像这样:

# No backslash before space needed, as the entire sting is quoted with "
filesDirName="/C/Users/OM SAI RAM/HelloWorldSagar"
# echo allows multiple parameter, so it worked by chance
# You should quote it anyway
echo "${filesDirName}"
echo "cd ${filesDirName}"
# quote the parameter
cd "${filesDirName}"

经验法则:如果有疑问,请引用变量。

BTW:将代码缩进 4 个空格,因此它显示为代码块

相关内容