Existen dos formas de crear un scrip con parámetro:

Usado “getopts” que está integrado en el shell Bash, puede trabajar con letras de opción de un solo carácter (como las banderas simples -a y -b, así como -c foo y –f nginx.conf. Las opciones de una sola letra se conocen como switches.

Sin embargo, a veces es útil, conveniente o incluso necesario utilizar nombres de opciones más largos, como –filename o –sourceip. El comando “getopts” incorporado en el shell no soporta esas opciones, sin embargo, el comando “getopt” de GNU, que es un comando externo (no incorporado en el shell) soporta estilos más largos así como con la forma corta y normalmente se usan para asignar parámetros.

Las opciones de getopt

-a, Permita que las opciones largas comiencen con un solo ‘-‘.

-o Definen el inicio de los caracteres que se usaran como argumentos cortos como -a.

-l Definen el inicio de los argumentos largos, como –help.

-n, Nombre del script que se muestra cuando existe un error. Por ejemplo

 

aurlenscript: unrecognized option '-g'

Parte del código se tomó de https://www.shellscript.sh/tips/getopt/, recomendable leer.

El siguiente scrip, usa el ejemplo muestra cómo usar getopt para analizar diferentes opciones cortas y largas. Si se provee un argumento no definido en getopt, se mostrara la ayuda (uso). Todo los parámetros extras son descartados.

 

# Call getopt to validate the provided input. 

scriptName=$(basename -- "$0")

uso()
{
printf "Usage of $scriptName\n\n"
printf "
ARGUMENT, DESCRIPTION\n	
-h, show this help\n
-i, Interface\n
-f, Configuration file\n
--env, prod | dev \n
-dst , Destinaion Ip\n
"|column -t -s ','	
}

#Like getopts, getopt uses the colon (:) to indicate that an argument expects a value, like "-d=river" rather than a simple "-d." So here we can see that "-o abc:d:" means "short options abcd, of which c: and d: require a value."

options=$(getopt -a -n aurlenscript -o i,f:, --long env:,dst: -- "$@")

#Si no se encontro ningun parametro valido, nostrar la ayuda.
ValidParameter=$?

if [ "$ValidParameter" != "0" ]; then
	uso
fi

eval set -- "$options"

printf "Parsed arguments are $options\n"

#shift; The arg is next in position args
while true; do

  case "$1" in
    -i)
	printf "\n -i was triggered "
	printf "\n Execute code of i"
	shift # Delete the switch from the stack
	printf "\n Parameters remaining are: $@" #Mostrar que paratros quedan en el stack
      ;;
    -h)
	printf "\n show help"
	uso
    ;;
    -f)
      printf "\n-f was triggered. was declared as f: should have a value, otherwise will show an error."
	  shift 2
	  printf "\nParameters remaining are: $@"
	;;

    --env)
      printf "\n --env or -env  was triggered. was declared as env: should have a value, otherwise will show an error."
	  shift 2 
	  printf "\n Parameters remaining are: $@"
	;;
    --dst)
      printf "\n--sdp was triggered. dst 10.253.253.2"
	  shift 2
	;;
	# -- means the end of the arguments; drop this, and break out of the while loop
	--)
        shift
		break
    ;;
	*)
		printf "\nInvalid parameter $1. try -h for help"
		uso
		exit 1
   ;;
  esac
done

 

Ejemplo de ejecución

 

 

[aurlen@monitor tmp]$ ./arguments.sh -i
Parsed arguments are  -i --

 -i was triggered
 Execute code of i
 Parameters remaining are: --[aurlen@monitor tmp]$
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$ ./arguments.sh -f
aurlenscript: option requires an argument -- 'f'
Usage of arguments.sh

ARGUMENT   DESCRIPTION
-h         show this help
-i         Interface
-f         Configuration file
--env      prod | dev
-dst       Destinaion Ip
Parsed arguments are  --
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$ ./arguments.sh --env
aurlenscript: option '--env' requires an argument
Usage of arguments.sh

ARGUMENT   DESCRIPTION
-h         show this help
-i         Interface
-f         Configuration file
--env      prod | dev
-dst       Destinaion Ip
Parsed arguments are  --
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$ ./arguments.sh --env  prod
Parsed arguments are  --env 'prod' --

 --env or -env  was triggered. was declared as env: should have a value, otherwise will show an error.
 Parameters remaining are: --[aurlen@monitor tmp]$
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$ ./arguments.sh -f ninginx.conf
Parsed arguments are  -f 'ninginx.conf' --

-f was triggered. was declared as f: should have a value, otherwise will show an error.
Parameters remaining are: --[aurlen@monitor tmp]$
[aurlen@monitor tmp]$
[aurlen@monitor tmp]$