简体   繁体   中英

BASH Shell named command line arguments

Can some please help how to pass named command line arguments to my shell script. Something like below.

./myOwnShellScript.sh -name Thor -tool Hammer 

Below is one way to implement

#!/bin/bash

#################################################################################################
# Script name  - myOwnShellScript.sh
# Description  - This script is used to implement my own logic.
# Author  - Tony 
#################################################################################################



function usage(){
  echo "Here is usage..."
  echo "./myOwnShellScript.sh -name <<Name of your hero>> -tool <<your hero's tool>>"
}

function paramMap(){
    declare -A params=( ["name"]="name" ["tool"]="tool" )
    paramVarName="${params[${1}]}"
    [ -z "${paramVarName}" ] && echo "info" || echo "${paramVarName}"
}
####################################################################################
#----------------------------------------------------------------------------------#
#             Main starts, the script execution starts here.                       #
#----------------------------------------------------------------------------------#
####################################################################################
export TERM="xterm"
clear
trap "exit 1" TERM
export TOP_PID=$$

CURR_TIME=$(date +"%Y-%m-%d-%T")
echo -e "\n**********************************************"
echo -e "\n myOwnShellScript.sh Script Started ${CURR_TIME}"
echo -e "\n**********************************************"

##################################################################################################
# Variable Declaration
##################################################################################################
#Read command line parameters and set script variables.
while [ $# -gt 0 ]; do
   if [[ $1 == *"-"* ]]; then
        v="${1/-/}"
        p=$(paramMap ${v})
        paramValue=$([ -z "$2" ] && echo "1" || echo "$2")
        declare $p="${paramValue}"
   fi
  shift
done

echo "Here is your hero ${name}"
echo "His tool is ${tool}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM