- 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.
推薦閱讀
- 極簡AI入門:一本書讀懂人工智能思維與應用
- Cloud Analytics with Microsoft Azure
- Learning Social Media Analytics with R
- RPA:流程自動化引領數(shù)字勞動力革命
- RPA(機器人流程自動化)快速入門:基于Blue Prism
- Photoshop CS5圖像處理入門、進階與提高
- 重估:人工智能與賦能社會
- 電動汽車驅動與控制技術
- Windows 7故障與技巧200例
- 菜鳥起飛電腦組裝·維護與故障排查
- 納米集成電路制造工藝(第2版)
- 計算機應用基礎學習指導與練習(Windows XP+Office 2003)
- 渲染王3ds Max三維特效動畫技術
- 工業(yè)機器人應用系統(tǒng)三維建模
- 工程地質(zhì)地學信息遙感自動提取技術