检查目录中是否只有两种类型的文件之一

Check if there is only one of two types of files in a directory

我有一个脚本可以检查目录中是否只有一个文件。但是,我不知道如何检查该目录中是否只有一个可执行文件(无文件扩展名)或脚本(.sh)。这是我目前拥有的:

loc=(/Applications/*)
APPROOTDIR="${loc[RANDOM % ${#loc[@]}]}/"
APPDIR="${APPROOTDIR}Contents/MacOS/"
echo "APPROOTDIR is ${APPROOTDIR}"
echo "APPDIR is ${APPDIR}"
FIAD=$(ls ${APPDIR})
if [ `ls -1 ${APPDIR}* 2>/dev/null | wc -l ` == 1 ]; then
    echo "One executable or script: ${FIAD}"
else
    echo "Not one executable or script: ${FIAD}"
fi

有人知道我该怎么做吗?

Don't parse ls,用目录条目填充另一个数组并改为处理它。

shopt -s nullglob
# set up loc, APPDIR, etc. here
ent=("$APPDIR"*)
if [[ ${#ent[@]} -eq 1 && ( $ent = *.sh || -x $ent ) ]]; then
  echo 'One executable or script: '
else
  echo 'Not one executable or script: '
fi
printf '%q\n' "${ent[@]#"$APPDIR"}"

注意全大写的变量名是为shell保留的,建议使用小写或混合大小写的变量名。