Shell脚本含空格路径的参数扩展问题求助
解决Shell脚本中含空格路径的目录空值判断问题
你的问题出在ls -A $workdir这部分:当路径包含空格时,未加引号的$workdir会被Shell拆分成多个参数传递给ls,导致ls无法正确识别完整路径,进而让后续的空值判断逻辑失效。
直接修复方案
只需要给ls命令中的$workdir加上双引号,确保路径作为单个参数被解析:
#!/bin/bash workdir=${1:-$(pwd)} if [ -d "$workdir" ]; then # 给$workdir加上双引号,修复含空格路径的解析问题 if [ -z "$(ls -A "$workdir")" ]; then echo "Working directory is set to: $workdir" else echo "Working directory is not empty!" read -p "Do you want to continue? (y/n) " choice if [[ "$choice" == [yY] ]]; then echo "Continuing..." elif [[ "$choice" == [nN] ]]; then echo "Exiting." exit 0 else echo "Invalid choice. Please enter y or n." exit 1 fi fi else echo "Creating and setting as working directory: $workdir" mkdir -p "$workdir" fi mkdir -p "${workdir}"/{code,data,docs,logs,outs,temp} mkdir -p "${workdir}/code/utils" mkdir -p "${workdir}/data/{raw,processed}"
更健壮的替代方案(推荐)
用ls判断目录是否为空并不总是可靠(比如文件名包含换行符时会误判),可以改用Shell的文件通配符来判断,更稳定:
#!/bin/bash workdir=${1:-$(pwd)} if [ -d "$workdir" ]; then # 启用nullglob:当通配符匹配不到文件时返回空列表而非原字符串 shopt -s nullglob # 匹配目录下所有非隐藏文件 files=("$workdir"/*) # 匹配目录下所有隐藏文件 hidden_files=("$workdir"/.*) # 合并两个数组的长度,判断是否存在文件 if [ $(( ${#files[@]} + ${#hidden_files[@]} )) -eq 0 ]; then echo "Working directory is set to: $workdir" else echo "Working directory is not empty!" read -p "Do you want to continue? (y/n) " choice if [[ "$choice" == [yY] ]]; then echo "Continuing..." elif [[ "$choice" == [nN] ]]; then echo "Exiting." exit 0 else echo "Invalid choice. Please enter y or n." exit 1 fi fi # 恢复nullglob的默认设置(可选,如果你后续不需要这个特性) shopt -u nullglob else echo "Creating and setting as working directory: $workdir" mkdir -p "$workdir" fi mkdir -p "${workdir}"/{code,data,docs,logs,outs,temp} mkdir -p "${workdir}/code/utils" mkdir -p "${workdir}/data/{raw,processed}"
这个方案通过直接统计目录下的文件数量来判断是否为空,避免了ls输出带来的潜在问题。
内容的提问来源于stack exchange,提问作者MKali
相关产品推荐
相关产品推荐

