Posts Tagged: ‘getopts’

Bash getops

August 30, 2012 Posted by admin

I converted a couple of old scripts to use get opts in order to make them flexiable so I thought it

would be fitting to just share a quick example with you guys.

 


#!/bin/bash

usage(){
cat << EOF
usage: $0 options

This script run excute the command on a remote server.

OPTIONS:
-h Show this message
-H Server to connect to
-C  Command to run on host
-v Verbose
EOF
}

HOST=
CMD=

while getopts "hH:C:v" OPTION
do
case $OPTION in
h)
usage
exit 1
;;
H)
HOST=$OPTARG
;;
C)
CMD=$OPTARG
;;
v)
VERBOSE=1
;;
?)
usage
exit
;;
esac
done

if [[ -z $HOST ]] || [[ -z $CMD ]]
then
usage
exit 1
fi

ssh -i ~/.ssh/id_rsa root@$HOST  "$CMD"