0

I use the following script to archive and delete user accounts.

The script expects a list of names as $1, but I'd like to have the script stop immediately if that first argument does not exist, and inform user with correct usage.

Your suggestions and any other improvements most appreciated!

Thanks, Dan

#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH

DESTDIR='/Volumes/UserStorage/Backups'
SRCDIR='/Volumes/UserStorage/Users'
LOG=`mktemp -t archive-accounts-XXXXX.log`
EMAIL_FROM='admin@example.com'
EMAIL_TO='admin@example.com'
EMAIL_SUBJ='Account archiving batch job report'


{
echo "Batch Begins...`date`"
echo "###############"
echo " "

while IFS= read -r line 
# If not first argument, script should exit with usage message 
do
    echo Starting account $line
    hdiutil create $DESTDIR/$line-$(date +%d-%m-%y).dmg -srcfolder $SRCDIR/$line
    RETCODE=$?
    if [ $RETCODE -eq 0 ]; then
  STATUS="Success"
  # rm -rf $SRCDIR/$line
  else
  STATUS="FAILED!"
  fi
  echo Exit Status: $STATUS
  echo Finished with account $line
  echo ""

done < $1

echo "###############"
echo "Batch complete! `date`" 

} >> $LOG 2>&1

cat $LOG | mailx -s "$EMAIL_SUBJ" $EMAIL_TO

exit 0
Dan
  • 931
  • 2
  • 18
  • 31
  • Could this be done by using a check like in the answer from this [other question](http://stackoverflow.com/questions/18568706/checking-number-of-arguments-bash-script)? – summea Mar 24 '14 at 23:51

2 Answers2

3

Here's a shorter alternative:

requiredArg=${1?no argument supplied, exiting...}

If $1 is not set, the text after ? will be output to stderr (with a preamble - see below), and the script will exit with code 1; if $1 is set, its value is simply assigned to variable requiredArg.

The preamble is the script's path (as invoked), the number of the error-triggering line, and the name of the unset parameter (variable); in the case at hand it might look like this:

./someScript: line 3: 1: no argument supplied, exiting...

If you find yourself checking in multiple places, it may be worth defining a small helper function as follows:

# Define helper function that outputs to stderr and exits with code 1.
die() { echo "$*" 1>&2; exit 1; }

Then you could use it as follows:

# Abort, if no arguments were passed.
(( $# > 0 )) || die "no argument supplied, exiting..."
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Adding the following is working:

if (($# == 0)); then
  echo "no argument supplied, exiting..."
exit 1
fi
Dan
  • 931
  • 2
  • 18
  • 31
  • 2
    This works, but error messages should be output to _stderr_, not stdout, so you should redirect the `echo` command with `1>&2`. – mklement0 Mar 25 '14 at 01:26