Script bash : arguments nommés
Utilisation d'arguments nommés au sein d'un script bash
26/08/2021

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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Il est ainsi facile d'étendre la liste des arguments pour convenir à ses besoins.