unix programming logic to check for directory
Shell scripting newbie here. Just wanted some input on my shell script. I basically want to launch a perl script from the shell script if a particular directory exists.
Is my logic sound? Are my checks ok?
if [ $# != 2 ]; then
echo "USAGE: ./mytest.sh <host> <name>" 2>&1
echo " ./mytest.sh foo101.test.in foo" 2>&1
exit 1
fi
#Directories
DIRDATE=`date '+%Y%m%d'`
BASE=/dumps
STGDIR=$BASE/temp/$DIRDATE
#Check if directory exists
if [ -d "$STGDIR" ] then
echo "$STGDIR directory exists!"
perl foobar.pl -n $1 -d $STGDIR/ -s $2
else
echo "$STGDIR directory not found! Create the directory"
mkdir $STGDIR || { echo开发者_运维知识库 'mkdir command failed' ; exit 1;}
if [ -d "STGDIR" ] then
echo "$STGDIR directory exists!"
perl foobar.pl -n $1 -d $STGDIR/ -s $2
fi
No problems but it can all be simplified like this:
if [ $# != 2 ]; then
echo "USAGE: $0 <host> <name>" 2>&1
echo " $0 foo101.test.in foo" 2>&1
exit 1
fi
#Directories
DIRDATE=$(date '+%Y%m%d')
BASE=/dumps
STGDIR=$BASE/temp/$DIRDATE
# create directory $STGDIR if needed
[ ! -d "$STGDIR" ] && ( mkdir "$STGDIR" || { echo 'mkdir command failed'; exit 1; } )
# execute your perl script
perl foobar.pl -n $1 -d $STGDIR/ -s $2
- good indenting
- good variable names
- good input checking
(you might want to check that your $1 and $2 inputs are correct before running a script that might blow up if you have wrong values) good to wrap vars in dbl-quotes "$DIR"
deprecated use of back-tic command substitution. Use $( cmd )
- message should be "Trying to create dir ..." or simliar (but very minor issue)
- on the first if block, if you cant create the dir, then exit
- the intent there is why have the call to perl in 2 places. move it outside of the if/then/else block so it only executes if you haven't exited with an error above. It is duplicate code as is, and if your script gets a lot bigger, you may modify one copy of that line, and not the other.
- per kurumi, missing fi
I hope this helps.
Not really critical but you may want to change your backticks to $()
if your shell supports it. You left out your closing fi
in the inner if
construct
精彩评论