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ましたが、それもうまくいきません。何か案は?

4

1 に答える 1

0

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 自体と一致しなくなります。

于 2012-07-29T03:00:28.703 に答える