2012-07-28 57 views
1

下面是一个较大的脚本的片段,它导出用户指定目录的子目录列表,并在用户指定的另一个用户指定的目录中提示用户之前提示用户目录。从文件列表变量中删除所有非目录

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,但那也行不通。 任何想法?

回答

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阻止查找匹配$ COPY_DIR本身。

+0

完美!它工作得很好。谢谢。 – reap3r119 2012-08-03 17:02:57

相关问题