Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH if directory contains files or doesn't

Tags:

bash

shell

I created a script that executes some commands based on a condition. If directory contains files then run "screen -r" anything else run "screen". Problem is screen sometimes gets executed even when the directory contains files.

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

What I want to do is refine it and break it down into two statements. If directory contains files then run screen-r" & if a directory doesn't contain files run "screen"

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

&

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

Maybe even a statement that executes based on # of file. If directory contains X amount of files.

Can somebody help me out with this? I hope I explained what I want thoroughly.

Thanks,

Geofferey

Again thank you for all your help, I got it all working now. Here is the final script. It's for the iPhone and an app I'm making called 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
like image 296
Geofferey Avatar asked Jul 20 '13 20:07

Geofferey


1 Answers

find could be helpful here:

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

UPD: what is -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.

So, -gt is "greater than" boolean function.

like image 131
ДМИТРИЙ МАЛИКОВ Avatar answered Oct 03 '22 07:10

ДМИТРИЙ МАЛИКОВ