2013-07-20 78 views
2

我创建了一个脚本,该脚本根据条件执行一些命令。如果目录包含文件,然后运行“屏幕-r”其他任何运行“屏幕”。问题是屏幕有时甚至在目录包含文件时被执行。BASH如果目录包含文件或者不包含

我想要做的就是改进它并将其分解为两个语句。如果目录包含文件,然后运行的屏幕-R” &如果目录中不包含的文件运行‘屏幕’

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

&

if ["$(directory without files)"] ; then 
screen 
fi 

甚至,其基于文件的#声明。如果目录中包含的文件X量。

有人可以帮助我吗?我希望我解释什么,我想彻底。

个谢谢,

Geofferey

再次感谢您对您的帮助,我得到了这一切,现在的工作。这是最后的脚本。这是为iPhone和我正在制作的应用程序称为MobileTerm Backgrounder。

#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 

回答

2

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. 

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

+0

你能解释一下-gt选项吗? – Geofferey

+0

所以这就好比如果文件数量大于0,所以如果我想要一个命令执行目录的文件= 0时,我会我们-eq? – Geofferey

+0

看来发现需要更长的时间来执行。 – Geofferey

0

我会用lswc这样:

if [ $(ls -A "$DIR" | wc -l) -gt 0 ]; then 
    screen -r 
else 
    screen 
fi 

你有双引号的$DIR变量,否则你就必须使用包含空格的目录名称的问题。

+0

究竟是如何我只是试图使用其他人的信息:) – Geofferey

+0

什么与我的报价?注意我的第一个例子main命令是如何包装在引号中的?为什么? – Geofferey

+0

您必须双引号'$ DIR'变量,因此'ls'将其视为单个目录名称。引用所有“$(...)”在这种情况下不起作用,因为'ls'仍然将'$ DIR'视为未加引号。 –