https://www.shellscript.sh/

Check is variable empty

1
2
3
4
5
if [[ -z $myvar ]]; then
echo "myvar is empty"
else
"myvar is $myvar"
fi
Reference:

Get current executable filename

1
echo "current filename is `basename $0`"
Reference:

Get first file in a directory

1
ls *.php | head -1
Reference:

Get modified date (in unix timestamp) of a file

1
echo `stat -f "%m" myfile.php`
Reference:

Get the latest files in a directory

1
2
3
4
5
6
7
8
9
10
# Get the first file of a directory
latest_file=`ls /path/to/your/files/*.php | head -1`
# loop through all files
for f in /path/to/your/files/*.php; do
# compare the file last modified date
if [ `stat -f "%m" $f` -gt `stat -f "%m" $latest_file` ]; then
latest_file=$f
fi
done
echo "latest file $latest_file : `stat -f "%m" $latest_file`"
Reference:

Check is directory exists

1
2
3
if [ -d "$DIRECTORY" ]; then
echo $DIRECTORY exists
fi

Or

1
2
3
if [ ! -d "$DIRECTORY" ]; then
echo $DIRECTORY not exists
fi
Reference:

Multiple condition in if statement

Example below shows to get some folders in current directory and exclude some of that

1
2
3
4
5
6
7
8
9
10
#!/bin/bash
for x in ./*; do
if [ -d $x ]; then # Only get the directory
proj=`basename $x`;
if [[ $proj == "excluded_1" || $proj == "excluded_2" || $proj == "excluded_3" ]]; then
continue
fi
echo $proj;
fi
done

NOTE: for multiple conditions, must use double bracket

References:

Get current directory

1
currdir="`dirname $0`"
Reference: