bash - Check argument exists before proceeding -


i use following script archive , delete user accounts.

the script expects list of names $1, i'd have script stop if first argument not exist, , inform user correct usage.

your suggestions , other improvements 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 usage message      echo starting account $line     hdiutil create $destdir/$line-$(date +%d-%m-%y).dmg -srcfolder $srcdir/$line     retcode=$?     if [ $retcode -eq 0 ];   status="success"   # rm -rf $srcdir/$line   else   status="failed!"   fi   echo exit status: $status   echo finished account $line   echo ""  done < $1  echo "###############" echo "batch complete! `date`"   } >> $log 2>&1  cat $log | mailx -s "$email_subj" $email_to  exit 0 

here's shorter alternative:

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

if $1 not set, text after ? output stderr (with preamble - see below), , script exit code 1; if $1 is set, value assigned variable requiredarg.

the preamble script's path (as invoked), number of error-triggering line, , name of unset parameter (variable); in case @ hand might this:

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

if find checking in multiple places, may worth defining small helper function follows:

# define helper function outputs stderr , exits code 1. die() { echo "$*" 1>&2; exit 1; } 

then use follows:

# abort, if no arguments passed. (( $# > 0 )) || die "no argument supplied, exiting..." 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -