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

时间:2012-07-28 22:39:03

标签: 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,但这也行不通。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您永远不应该依赖ls的输出来提供文件名。请参阅以下内容,了解不解析lshttp://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本身。

相关问题