官术网_书友最值得收藏!

Understanding getopts

Command-line parameters passed along with commands are also called positional parameters. Many times, we need to pass options such as -f and -v along with a positional parameter.

Let's look at an example for passing the -x or-y options along with commands.

Write shell script getopt.sh, as follows:

#!/bin/bash 
 
USAGE="usage: $0 -x -y" 
 
while getopts :xy: opt_char 
do 
  case $opt_char in 
  x) 
    echo "Option x was called." 
    ;; 
  y) 
    echo "Option y was called. Argument called is $OPTARG" 
    ;; 
  ?) 
    echo "$OPTARG is not a valid option." 
    echo "$USAGE" 
    ;; 
  esac 
done 

Execute this program:

$ ./getopt.sh

You will learn about the switch and case statements in the next chapters. In this script, if option -x is passed, a case statement for x will be executed. If the -y option is passed, then a case statement for -y will be executed. If no option is passed, there will not be any output on the screen.

Let us run script with different options::

$ ./getopt.sh -x

The output is as follows:

Option y was called. Argument called is my_file.
$ ./getopt.sh -x -y my_file
Output:
Option x was called.
Option y was called. Argument called is my_file.
$ ./getopt.sh -y my_file -x
Output:
Option y was called. Argument called is my_file.
Option x was called.
主站蜘蛛池模板: 红原县| 宁远县| 耒阳市| 长丰县| 高安市| 广德县| 鸡西市| 都安| 岗巴县| 乐至县| 伽师县| 义马市| 吉木萨尔县| 依兰县| 丹巴县| 旅游| 上林县| 侯马市| 宣城市| 广南县| 峨边| 甘南县| 桂东县| 山阳县| 西青区| 柳江县| 壤塘县| 鄯善县| 崇文区| 宾阳县| 嘉鱼县| 湾仔区| 天祝| 玛纳斯县| 玉田县| 合水县| 丘北县| 沙洋县| 繁昌县| 阿勒泰市| 如东县|