Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use getopts?

Tags:

bash

getopts

what is the easiest, most straight forward, way to use getopts in bash script.

if i have a script called: myscript and it CAN take the the arguments: -p -r -s -x

if argument x then exit
if argument p then echo "port 10"
if argument s then add 2+2
if argument r then echo env 

This is a hypothetical script but I would just like to see an example of how this would be done.

like image 829
stackoverflow Avatar asked Feb 03 '26 03:02

stackoverflow


1 Answers

while getopts :xpsr opt; do
   case $opt in
     x ) exit                                ;;
     p ) echo port 10                        ;;
     s ) (( 2 + 2 ))                         ;;
     r ) echo env                            ;;
    \? ) echo "${0##*/}" [ -xpsr ]; exit 1   ;;
  esac
done
like image 144
Dimitre Radoulov Avatar answered Feb 04 '26 20:02

Dimitre Radoulov