BASH 如果目录包含文件或不包含文件

Geo*_*rey 5 bash shell

我创建了一个脚本,根据条件执行一些命令。如果目录包含文件,则运行“screen -r”,否则运行“screen”。问题是即使目录包含文件有时也会执行屏幕。

if [ "$(ls -A $DIR)" ]; then
screen -r
else
screen
fi
Run Code Online (Sandbox Code Playgroud)

我想要做的是对其进行改进并将其分解为两个语句。如果目录包含文件,则运行 screen-r" & 如果目录不包含文件,则运行 "screen"

if [ "$(ls -A $DIR)" ]; then
screen -r
fi
Run Code Online (Sandbox Code Playgroud)

&

if ["$(directory without files)"] ; then
screen
fi
Run Code Online (Sandbox Code Playgroud)

甚至可能是基于文件# 执行的语句。如果目录包含 X 个文件。

有人可以帮我解决这个问题吗?我希望我彻底解释了我想要什么。

谢谢,

杰弗里

再次感谢您的帮助,我现在一切正常。这是最终的脚本。它适用于 iPhone 和我正在制作的名为 MobileTerm 后台程序的应用程序。

#Sets up terminal environment? 

if [[ $TERM = network || -z $TERM ]]; then
export TERM=linux
fi

# This script automatically runs screen & screen -r (resume) based on a set of conditions. 

# Variable DIR (variable could be anything)

DIR="/tmp/screens/S-mobile"

# if /tmp/screens/S-mobile list files then run screen -x

if [ "$(ls -A $DIR)" ]; then
screen -x
fi

#if /tmp/screens/S-mobile contains X amount of files = to 0 then run screen -q

if [ $(ls -A "$DIR" | wc -l) -eq 0 ]; then
screen -q
fi
Run Code Online (Sandbox Code Playgroud)

ДМИ*_*КОВ 6

find 在这里可能会有所帮助:

if [[ $(find ${dir} -type f | wc -l) -gt 0 ]]; then echo "ok"; fi

UPD:是什么-gt

man bash-> / -gt/:

   arg1 OP arg2
          OP is one of -eq, -ne, -lt, -le, -gt, or -ge.  These arithmetic binary operators return true if  arg1  is  equal  to,  not
          equal  to,  less than, less than or equal to, greater than, or greater than or equal to arg2, respectively.  Arg1 and arg2
          may be positive or negative integers.
Run Code Online (Sandbox Code Playgroud)

所以,-gt是“大于”布尔函数。