by
48 7
0
5
2,869
15
Top 1% !
Popular
Famous
Tagged
Specified
Popularity: 5328th place
This snippet is Public
Languagebash
LicenseMIT_X11

Bash getops example

Simple example of argument parsing with getopts
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/418/Bash-getops-example?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
#!/bin/bash usage() { echo "" echo "$0 -f <csv|html> -i <IP address> -l" echo "" echo "Example:" echo " $0 -f html -i 172.16.88.83" echo " $0 -f csv -i 172.16.88.83 -l" } #default value FORMAT="csv" IPADDR="" LOAD=false while getopts ":f:i:l" optname do case "$optname" in "f") if [[ ${OPTARG} == "csv" || ${OPTARG} == "html" ]] ; then FORMAT="${OPTARG}" else echo "Output format not supported" usage exit 1 fi ;; "i") IPADDR="${OPTARG}" ;; "l") LOAD=true ;; "?") usage exit 1 ;; ":") echo "No argument value for option $OPTARG" ;; *) echo "Unknown error while processing options" ;; esac done # Mandatory arguments if [[ -z ${FORMAT} ]] || [[ -z ${IPADDR} ]] then usage exit 1 fi echo "format: $FORMAT" echo "ipaddr: $IPADDR" if [[ ${LOAD} == "true" ]] ; then echo "load: true" else echo "load: false" fi
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus