Script bash : arguments nommés

Utilisation d'arguments nommés au sein d'un script bash

26/08/2021

Bash
Arguments
Fonctions
article illustration

Pour donner un aspect pro à un script, il est intéressant d'utiliser des arguments nommés ceux-ci permettent d'assurer une constant et une facilité d'utilisation à l'utilisateur.

Dans sa réponse à la question : comment utiliser getops en bash, theBuzzyCoder explique parfaitement comment utiliser les arguments nommés.

#!/bin/bash
# code found on https://stackoverflow.com/questions/16483119/an-example-of-how-to-use-getopts-in-bash/52674277#52674277
# filename: commandLine.sh
# author: @theBuzzyCoder
showHelp() {
# `cat << EOF` This means that cat should stop reading when EOF is detected
cat << EOF
Usage: ./installer -v <espo-version> [-hrV]
Install Pre-requisites for EspoCRM with docker in Development mode
-h, -help, --help Display help
-v, -espo-version, --espo-version Set and Download specific version of EspoCRM
-r, -rebuild, --rebuild Rebuild php vendor directory using composer and compiled css using grunt
-V, -verbose, --verbose Run script in verbose mode. Will print out each step of execution.
EOF
# EOF is found above and hence cat command stops reading. This is equivalent to echo but much neater when printing out.
}
export version=0
export verbose=0
export rebuilt=0
# $@ is all command line parameters passed to the script.
# -o is for short options like -v
# -l is for long options with double dash like --version
# the comma separates different long options
# -a is for long options with single dash like -version
options=$(getopt -l "help,version:,verbose,rebuild,dryrun" -o "hv:Vrd" -a -- "$@")
# set --:
# If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters
# are set to the arguments, even if some of them begin with a ‘-’.
eval set -- "$options"
while true
do
case $1 in
-h|--help)
showHelp
exit 0
;;
-v|--version)
shift
export version=$1
;;
-V|--verbose)
export verbose=1
set -xv # Set xtrace and verbose mode.
;;
-r|--rebuild)
export rebuild=1
;;
--)
shift
break;;
esac
shift
done
view raw commandLine.sh hosted with ❤ by GitHub

Il est ainsi facile d'étendre la liste des arguments pour convenir à ses besoins.

A retenir

Il n'est pas immédiat d'utiliser les arguments nommés mais ceux-ci permettent une utilisation plus aisée pour l'utilisateur

Il est bon de définir à la fois des arguments courts et des arguments longs (-v ou --version) par exemple, cela rend l'utilisation encore plus rapide