Programming/Bash Script

Bash script argument parsing with getopts

쵸코아몬드 2020. 1. 23. 18:07

Bash script 실행 할 때, 다양한 option에 대한 argument를 넣고, parsing 하는 방법

 

#!/bin/bash

while getopts "hvf:" shortopt
do
	case $shortopt in 
    	h)
        	echo "Usage: $0 [-h] [-v] [-f file_name]"
            	echo "    -h: help"
            	echo "    -v: verbose"
            	echo "    -f filename: input file"
            	exit
            	;;
    	v)
        	VERBOSE=1
            	;;
        f)
        	FILE=$OPTARG
            	;;
        *)
        	echo "default settings"
            	;;
    esac
done

shortopt 가 OPTARG를 가지는 경우 ":"(Colon) 을 포함하고, 그외의 경우의 알파벳을 열거하여 while 문을 구성하면 된다.