linux - 从文件列表变量中删除所有非目录

标签 linux bash shell

下面是一个较大脚本的片段,该脚本导出用户指定目录的子目录列表,并在用户指定的另一个目录中创建具有相同名称的目录之前提示用户。

COPY_DIR=${1:-/}
DEST_DIR=${2}
export DIRS="`ls --hide="*.*" -m ${COPY_DIR}`"
export DIRS="`echo $DIRS | sed "s/\,//g"`"
if [ \( -z "${DIRS}" -a "${1}" != "/" \) ]; then 
  echo -e "Error: Invalid Input: No Subdirectories To Output\n"&&exit
elif [ -z "${DEST_DIR}" ]; then 
  echo "${DIRS}"&&exit
else
  echo "${DIRS}"
  read -p "Create these subdirectories in ${DEST_DIR}?" ANS
  if [ ${ANS} = "n|no|N|No|NO|nO" ]; then
    exit
  elif [ ${ANS} = "y|ye|yes|Y|Ye|Yes|YE|YES|yES|yeS|yEs|YeS" ]; then
    if [ ${COPYDIR} = ${DEST_DIR} ]; then
      echo "Error: Invalid Target: Source and Destination are the same"&&exit
    fi
    cd "${DEST_DIR}"
    mkdir ${DIRS}
  else 
    exit
  fi
fi

但是,命令 ls --hide="*.*"-m ${COPY_DIR} 也会打印列表中的文件。有没有办法改写这个命令,让它只打印出目录?我尝试了 ls -d,但这也不起作用。 有什么想法吗?

最佳答案

您永远不应该依赖 ls 的输出来提供文件名。关于不解析 ls 的原因,请参阅以下内容:http://mywiki.wooledge.org/ParsingLs

您可以使用 GNU find 的 -print0 选项安全地构建目录列表并将结果附加到数组。

dirs=() # create an empty array
while read -r -d $'\0' dir; do # read up to the next \0 and store the value in "dir"
   dirs+=("$dir") # append the value in "dir" to the array
done < <(find "$COPY_DIR" -type d -maxdepth 1 -mindepth 1 ! -name '*.*') # find directories that do not match *.*

-mindepth 1 阻止 find 匹配 $COPY_DIR 本身。

关于linux - 从文件列表变量中删除所有非目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11705232/

相关文章:

C++ ld 返回 1 退出状态

c++ - 如何使用 C++ 不使用 system() 删除除最后 10 个文件之外的所有文件

html - 通过 bash 从 html 中提取信息

linux - 增加多个文件名 Bash 的数量

python - 将列表作为变量从 bash 脚本传递给 python 脚本

shell - echo PATH $PATH\$PATH 有什么作用?

php - 使用 PHP 检查 IPv4/IPv6 地址是否已启动

linux - Docker 持续部署工作流程

linux - 当 Make 存在最终目标时如何不重新制作先决条件

bash - 如何使用 Bash 合并 Docker Compose 文件