Shell脚本如何拼接变量中含空格的文件夹路径(Firefox配置场景)
问题原因
Shell默认会按内部字段分隔符(IFS,默认包含空格、制表符、换行符)对未加双引号包裹的变量进行拆分,你直接遍历$firefoxProfiles变量时,路径里的空格就会被识别成分隔符,把一个完整路径拆成多个片段。
修复方案
方案1:find搭配while read(兼容性最好,适配Mac默认的bash 3.2、zsh环境)
直接通过管道把find的结果逐行传给read读取,每行就是一个完整路径,不会被空格拆分:
find "/Users/$userName/Library/Application Support/Firefox/Profiles" -name '*.default*' -type d | while read -r x; do echo "$x" # 此处添加对每个配置文件夹的处理逻辑 done
注意:read加-r参数是为了避免路径里有反斜杠时被转义丢失。
方案2:用数组存储结果(适配zsh、bash 4.0+版本)
直接把find的结果按行读入数组,每个数组元素就是完整路径:
# zsh 环境写法 firefoxProfiles=("${(@f)$(find "/Users/$userName/Library/Application Support/Firefox/Profiles" -name '*.default*' -type d)}") for x in "${firefoxProfiles[@]}"; do echo "$x" done # bash 4.0+ 环境写法 readarray -t firefoxProfiles < <(find "/Users/$userName/Library/Application Support/Firefox/Profiles" -name '*.default*' -type d) for x in "${firefoxProfiles[@]}"; do echo "$x" done
注意:遍历数组的时候一定要给${firefoxProfiles[@]}加双引号,否则还是会出现空格拆分的问题。
内容的提问来源于stack exchange,提问作者DarkKnight4251
相关产品推荐
相关产品推荐

