Bash脚本中含空格文件路径的可写性判断异常问题
Bash脚本中拖拽路径的可写性判断失败
现象
- 直接在Bash终端执行以下命令,正常输出
string:
[[ -w '/mnt/pictures/Albums/2025/03/Roll11 Portra400 35 : 01002/838680010002.jpg' ]] && echo "string"
- 将该路径赋值给变量后执行命令,正常输出
variable:
variable='/mnt/pictures/Albums/2025/03/Roll11 Portra400 35 : 01002/838680010002.jpg' [[ -w $variable ]] && echo "variable"
- 但运行以下脚本时,仅输出
string,不符合预期:
#!/usr/bin/env bash read -rp "Enter path to the image file: " image_file if [[ -w "${image_file}" ]]; then echo "variable" else [[ -w '/mnt/pictures/Albums/2025/03/Roll11 Portra400 35 : 01002/838680010002.jpg' ]] && echo "string" exit 1 fi exit
调试结果
使用bash -x调试脚本,输出如下:
+ read -rp 'Enter path to the image file: ' image_file Enter path to the image file: '/mnt/pictures/Albums/2025/03/Roll11 Portra400 35 : 01002/838680010002.jpg' + [[ -w '/mnt/pictures/Albums/2025/03/Roll11 Portra400 35 : 01002/838680010002.jpg' ]] + [[ -w /mnt/pictures/Albums/2025/03/Roll11 Portra400 35 : 01002/838680010002.jpg ]] + echo string string + exit 1
从调试日志能看到,拖拽输入的路径被自动加上了单引号,read命令把这些单引号也当作路径的一部分读取,导致[[ -w "${image_file}" ]]判断的是带单引号的路径,自然找不到文件,进入else分支。
解决方法
方法1:手动去除输入中的引号
修改脚本,在读取路径后移除首尾的单引号(可按需添加双引号处理):
#!/usr/bin/env bash read -rp "Enter path to the image file: " image_file # 移除首尾的单引号 image_file="${image_file#'\'}" image_file="${image_file%\'}" # 若需要处理双引号,可添加以下两行 # image_file="${image_file#\"}" # image_file="${image_file%\"}" if [[ -w "${image_file}" ]]; then echo "variable" else [[ -w '/mnt/pictures/Albums/2025/03/Roll11 Portra400 35 : 01002/838680010002.jpg' ]] && echo "string" exit 1 fi exit
方法2:关闭终端自动加引号功能
打开Konsole设置,找到文件拖拽相关选项,关闭“为路径添加引号”的开关,这样拖拽文件到终端时不会自动带上引号,脚本可直接读取正确路径。
方法3:用eval解析输入(谨慎使用)
若确定输入为可信路径,无恶意代码,可使用eval自动解析输入并去除引号:
#!/usr/bin/env bash read -rp "Enter path to the image file: " image_file eval image_file="$image_file" if [[ -w "${image_file}" ]]; then echo "variable" else [[ -w '/mnt/pictures/Albums/2025/03/Roll11 Portra400 35 : 01002/838680010002.jpg' ]] && echo "string" exit 1 fi exit
注意:eval会执行输入中的命令,若输入不可信存在安全风险,需谨慎使用。
内容的提问来源于stack exchange,提问作者ecotechie
相关产品推荐
相关产品推荐

