September 22, 2015

How to pass arguments to a Bash-script

1. Using getopts

1. Create new Shell Script

$ vi test.sh

2. Copy the following line into test.sh file

while getopts p:u:f:n:r: option
do
  case "${option}" in
    p) weblogic_password=${OPTARG};;
    u) weblogic_username=${OPTARG};;
    f) war_file=${OPTARG};;
    n) ws_name=${OPTARG};;
    r) ROLE_NAME=${OPTARG};;
  esac
done

echo ${weblogic_password}
echo $weblogic_username
echo $war_file
echo $ws_name
echo $ROLE_NAME

3.Run the script

$ chmod +x test.sh
$ ./test.sh -p weblogic_password -u weblogic_username -f war_file -n web_name -r role_name

2. Using environment variables

See the example below:
#!/bin/sh

OIFS=$IFS;
IFS=",";

usage() {
    cat <<EOF
Usage: $0 [options] [--] [file...]

Arguments:

  -h, --help
    Display this usage message and exit.

  -f <val>, --foo <val>, --foo=<val>
    Documentation goes here.

  -b <val>, --bar <val>, --bar=<val>
    Documentation goes here.

  --
    Treat the remaining arguments as file names.  Useful if the first
    file name might begin with '-'.

  file...
    Optional list of file names.  If the first file name in the list
    begins with '-', it will be treated as an option unless it comes
    after the '--' option.
EOF
}

# handy logging and error handling functions
log() { printf '%s\n' "$*"; }
error() { log "ERROR: $*" >&2; }
fatal() { error "$*"; exit 1; }
usage_fatal() { error "$*"; usage >&2; exit 1; }

# parse options
foo="foo default value goes here"
bar="bar,default,value,goes,here"
barArray=($bar)

while [ "$#" -gt 0 ]; do
    arg=$1
    case $1 in
        # convert "--opt=the value" to --opt "the value".
        # the quotes around the equals sign is to work around a
        # bug in emacs' syntax parsing
        --*'='*) shift; set -- "${arg%%=*}" "${arg#*=}" "$@"; continue;;
        -f|--foo) shift; foo=$1;;
        -b|--bar) shift;
                  bar=$1;
                  barArray=($bar);
                  ;;
        -h|--help) usage; exit 0;;
        --) shift; break;;
        -*) usage_fatal "unknown option: '$1'";;
        *) break;; # reached the list of file names
    esac
    shift || usage_fatal "option '${arg}' requires a value"
done
#arguments are now the file names


echo "foo=" $foo
echo "bar=" $bar
echo "barArray size=" ${#barArray[@]}
for ((i=0; i<${#barArray[@]}; ++i)); do
  echo "bar $i: ${barArray[$i]}";
done

IFS=$OIFS;

1 comment:

landorzahnow said...

Casinos near the Casino & Hotel in San Diego - Mapyro
Find 성남 출장안마 Casinos Near The Casino & 광주 출장안마 Hotel in San Diego near the 논산 출장마사지 Casino & Hotel in 진주 출장안마 San Diego. Nearby: Casino & Hotel. Directions to 삼척 출장마사지 Casino.