셸 스 크 립 트 의 매개 변수 옵션

 getopts
base 셸 의 내 장 된 명령 을 위해 셸 의 인자 확장 을 제공 합 니 다. 셸 스 크 립 트 의 옵션 을 가 져 올 수 있 고 셸 스 크 립 트 옵션 뒤에 있 는 인 자 를 가 져 올 수 있 으 며 스 크 립 트 에서 호출 할 수 있 습 니 다.
 
getopts optstring name [arg]
1. optstring 스 크 립 트 가 사용 할 수 있 는 매개 변 수 를 정의 합 니 다.
2. 짧 은 옵션 만 지원 하고 긴 옵션 은 지원 하지 않 습 니 다.
3. 옵션 뒤의 인 자 를 사용 하려 면 옵션 뒤에 콜론 (:) 을 추가 하면 됩 니 다.
4. 기본 적 인 상황 에서 하나의 인자 만 가 져 올 수 있 습 니 다.
eg1:

  
  
  
  
  1. [root@localhost ~]# cat test.sh  
  2. #!/bin/bash 
  3. getopts a OPT 
  4.    echo $OPT 
  5. [root@localhost ~]# ./test.sh -a 

* 옵션 뒤의 인 자 를 사용 하려 면 옵션 뒤에 콜론 (:) 을 추가 하면 됩 니 다.
eg2:

  
  
  
  
  1. [root@localhost ~]# cat test.sh  
  2. #!/bin/bash 
  3. getopts a: OPT 
  4.    echo $OPT 
  5.    echo $OPTARG 
  6. [root@localhost ~]# ./test.sh -a "this is a" 
  7. this is a 

* 잘못된 정 보 를 출력 하지 않 으 려 면 모든 옵션 에 콜론 (:) 을 추가 하면 됩 니 다.
eg3:

  
  
  
  
  1. [root@localhost ~]# cat a.sh  
  2. #!/bin/bash 
  3. getopts a: OPT 
  4.    echo $OPT 
  5.    echo $OPTARG 
  6. [root@localhost ~]# ./a.sh -b 
  7. ./a.sh: illegal option -- b 
  8. [root@localhost ~]# cat a.sh  
  9. #!/bin/bash 
  10. getopts :a: OPT 
  11.    echo $OPT 
  12.    echo $OPTARG 
  13. [root@localhost ~]# ./a.sh -b 

* 여러 옵션 을 사용 하려 면 순환 문 구 를 사용 해 야 합 니 다.
eg4:

  
  
  
  
  1. [root@localhost ~]# cat a.sh  
  2. #!/bin/bash 
  3. while getopts ":a:b:" OPT;do 
  4.     case $OPT in 
  5.         a) 
  6.           echo $OPT 
  7.           echo $OPTARG 
  8.           ;; 
  9.         b) 
  10.           echo $OPT 
  11.           echo $OPTARG 
  12.           ;; 
  13.         *) 
  14.           echo "wrong option" 
  15.           ;; 
  16.     esac 
  17. done 
  18. [root@localhost ~]# ./a.sh -a "this is a" 
  19. this is a 
  20. [root@localhost ~]# ./a.sh -b "this is b"  
  21. this is b 
  22. [root@localhost ~]# ./a.sh -c "this is c"  
  23. wrong option 

 

좋은 웹페이지 즐겨찾기