- Learning Linux Shell Scripting
- Ganesh Naik
- 218字
- 2021-06-25 22:02:57
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.
推薦閱讀
- 電氣自動化專業(yè)英語(第3版)
- Word 2000、Excel 2000、PowerPoint 2000上機指導與練習
- 火格局的時空變異及其在電網(wǎng)防火中的應用
- 軟件架構(gòu)設(shè)計
- 機器學習與大數(shù)據(jù)技術(shù)
- 模型制作
- 流處理器研究與設(shè)計
- 計算機網(wǎng)絡(luò)安全
- 工業(yè)機器人安裝與調(diào)試
- 電腦上網(wǎng)輕松入門
- 液壓機智能故障診斷方法集成技術(shù)
- The DevOps 2.1 Toolkit:Docker Swarm
- 數(shù)字多媒體技術(shù)基礎(chǔ)
- 基于Proteus的PIC單片機C語言程序設(shè)計與仿真
- 從機器學習到無人駕駛