TranslateProject/published/201406/Bash Getopts--Scripts with Command Line Options.md
wxy a71aa7de9e renamed: 10 Database Tools For Linux Users To Use!.md -> 201406/10 Database Tools For Linux Users To Use!.md
renamed:    10 Linux Platforms Meant For Embedded Systems.md -> 201406/10 Linux Platforms Meant For Embedded Systems.md
	renamed:    20140527 4MLinux 9.0 Beta Is a 55 MB Operating System That Has It All.md -> 201406/20140527 4MLinux 9.0 Beta Is a 55 MB Operating System That Has It All.md
	renamed:    20140527 A Complete Historical Timeline of Linux Evolution.md -> 201406/20140527 A Complete Historical Timeline of Linux Evolution.md
	renamed:    20140528 Setup Backup Server Using Bacula And Webmin On Ubuntu 14.04.md -> 201406/20140528 Setup Backup Server Using Bacula And Webmin On Ubuntu 14.04.md
	renamed:    20140528 Why We Shouldn't Accept Bad Linux Ports.md -> 201406/20140528 Why We Shouldn't Accept Bad Linux Ports.md
	renamed:    20140529 Add Windows Like Bottom Taskbar In Ubuntu Unity 14.04.md -> 201406/20140529 Add Windows Like Bottom Taskbar In Ubuntu Unity 14.04.md
	renamed:    20140529 Command Line Tuesdays--The Introductory.md -> 201406/20140529 Command Line Tuesdays--The Introductory.md
	renamed:    20140529 How To Share Disks In VirtualBox Between Linux Guest OS.md -> 201406/20140529 How To Share Disks In VirtualBox Between Linux Guest OS.md
	renamed:    20140529 Install RainLoop Webmail (A Web Based Email Client) using 'Nginx and Apache' in Arch Linux.md -> 201406/20140529 Install RainLoop Webmail (A Web Based Email Client) using 'Nginx and Apache' in Arch Linux.md
	renamed:    20140529 What is a good terminal emulator on Linux.md -> 201406/20140529 What is a good terminal emulator on Linux.md
	renamed:    20140529 Why No Flash Support for Linux Is Good for Open Source.md -> 201406/20140529 Why No Flash Support for Linux Is Good for Open Source.md
	renamed:    20140530 Fix 'Cannot Add PPA' Error In Ubuntu 14.04 and Linux Mint.md -> 201406/20140530 Fix 'Cannot Add PPA' Error In Ubuntu 14.04 and Linux Mint.md
	renamed:    20140530 How To Install Linux On A MacBook Pro Retina.md -> 201406/20140530 How To Install Linux On A MacBook Pro Retina.md
	renamed:    20140530 Linux script command--A recorder inside your Terminal.md -> 201406/20140530 Linux script command--A recorder inside your Terminal.md
	renamed:    20140603 App Grid Is A Superior Ubuntu Software Center Alternative.md -> 201406/20140603 App Grid Is A Superior Ubuntu Software Center Alternative.md
	renamed:    20140603 Linux Foundation to donate portion of membership fees to Code.org.md -> 201406/20140603 Linux Foundation to donate portion of membership fees to Code.org.md
	renamed:    20140603 Write your first Linux Kernel module.md -> 201406/20140603 Write your first Linux Kernel module.md
	renamed:    20140604 Command line secrets.md -> 201406/20140604 Command line secrets.md
	renamed:    20140604 Setup Virtual Hosts In Apache On Ubuntu 14.04 LTS.md -> 201406/20140604 Setup Virtual Hosts In Apache On Ubuntu 14.04 LTS.md
	renamed:    20140607 Cup 2014 Brazil--Watch FIFA World Cup 2014 Competition in Your Linux Desktop.md -> 201406/20140607 Cup 2014 Brazil--Watch FIFA World Cup 2014 Competition in Your Linux Desktop.md
	renamed:    20140607 How To Extract Images From Videos Using ffmpeg.md -> 201406/20140607 How To Extract Images From Videos Using ffmpeg.md
	renamed:    20140607 How To Install iCup 2014 In Linux.md -> 201406/20140607 How To Install iCup 2014 In Linux.md
	renamed:    20140607 Linux--Bash Delete All Files In Directory Except Few.md -> 201406/20140607 Linux--Bash Delete All Files In Directory Except Few.md
	renamed:    20140607 New OpenSSL breach is no Heartbleed-but needs to be taken seriously.md -> 201406/20140607 New OpenSSL breach is no Heartbleed-but needs to be taken seriously.md
	renamed:    20140607 Nuvola Player 2.4.0 Released -- A Online Cloud Music Player for Linux.md -> 201406/20140607 Nuvola Player 2.4.0 Released -- A Online Cloud Music Player for Linux.md
	renamed:    20140607 Practical Interview Questions and Answers on Linux Shell Scripting.md -> 201406/20140607 Practical Interview Questions and Answers on Linux Shell Scripting.md
	renamed:    20140607 Steam Hits The Big 500 For Linux Games.md -> 201406/20140607 Steam Hits The Big 500 For Linux Games.md
	renamed:    20140607 Ubuntu One Formally Shuts Down.md -> 201406/20140607 Ubuntu One Formally Shuts Down.md
	renamed:    20140609 How To Know If Your System Has USB 3.0 Port In Linux [Quick Tip].md -> 201406/20140609 How To Know If Your System Has USB 3.0 Port In Linux [Quick Tip].md
	renamed:    20140609 Open Source LDAP Solutions.md -> 201406/20140609 Open Source LDAP Solutions.md
	renamed:    "20140609 OpenELEC 4.0.4 \347\216\260\345\267\262\345\217\221\345\270\203, \345\237\272\344\272\216 XBMC 13.1 \342\200\234Gotham\342\200\235.md" -> "201406/20140609 OpenELEC 4.0.4 \347\216\260\345\267\262\345\217\221\345\270\203, \345\237\272\344\272\216 XBMC 13.1 \342\200\234Gotham\342\200\235.md"
	renamed:    20140610 How to set up Internet connection sharing with iptables on Linux.md -> 201406/20140610 How to set up Internet connection sharing with iptables on Linux.md
	renamed:    20140610 IPFire 2.13 Core 78 Linux Firewall OS Receives OpenSSL Fixes.md -> 201406/20140610 IPFire 2.13 Core 78 Linux Firewall OS Receives OpenSSL Fixes.md
	renamed:    20140610 Open Source SDN Project OpenDaylight Adds New Members.md -> 201406/20140610 Open Source SDN Project OpenDaylight Adds New Members.md
	renamed:    20140610 Top 7 Desktop Environment For Linux.md -> 201406/20140610 Top 7 Desktop Environment For Linux.md
	renamed:    20140611 HTG Explains--What' s the Difference Between Linux and BSD.md -> 201406/20140611 HTG Explains--What' s the Difference Between Linux and BSD.md
	renamed:    20140611 How to Prevent Other Users From Accessing Your Home Directory in Ubuntu 14.04.md -> 201406/20140611 How to Prevent Other Users From Accessing Your Home Directory in Ubuntu 14.04.md
	renamed:    20140612 Command Line Tuesdays--Part One.md -> 201406/20140612 Command Line Tuesdays--Part One.md
	renamed:    20140612 Dpkg Vulnerabilities Closed in Ubuntu 14.04.md -> 201406/20140612 Dpkg Vulnerabilities Closed in Ubuntu 14.04.md
	renamed:    20140616 How To Install Numix Icon Theme In Fedora 20.md -> 201406/20140616 How To Install Numix Icon Theme In Fedora 20.md
	renamed:    20140616 Ubuntu Desktop Next 14.10 Images Available to Download.md -> 201406/20140616 Ubuntu Desktop Next 14.10 Images Available to Download.md
	renamed:    20140616 Ubuntu for Phones Activated on 10,000 Devices.md -> 201406/20140616 Ubuntu for Phones Activated on 10,000 Devices.md
	renamed:    20140617 14 Apps To Boost Ubuntu.md -> 201406/20140617 14 Apps To Boost Ubuntu.md
	renamed:    20140619 Improve Battery Life with Laptop Mode Tools 1.65.md -> 201406/20140619 Improve Battery Life with Laptop Mode Tools 1.65.md
	renamed:    20140619 Red Hat to Acquire eNovance, Focus Together on OpenStack.md -> 201406/20140619 Red Hat to Acquire eNovance, Focus Together on OpenStack.md
	renamed:    20140620 Celebrating 30 Years of X.md -> 201406/20140620 Celebrating 30 Years of X.md
	renamed:    20140620 ENCRYPT DNS TRAFFIC IN LINUX WITH DNSCRYPT (VIA OPENDNS).md -> 201406/20140620 ENCRYPT DNS TRAFFIC IN LINUX WITH DNSCRYPT (VIA OPENDNS).md
	renamed:    20140620 How to enable testing and unstable repository on Debian.md -> 201406/20140620 How to enable testing and unstable repository on Debian.md
	renamed:    20140625 Canonical Debuts 'Orange Box' for Ubuntu OpenStack Cloud Demos.md -> 201406/20140625 Canonical Debuts 'Orange Box' for Ubuntu OpenStack Cloud Demos.md
	renamed:    8 examples of findmnt command to check mounted file systems on Linux.md -> 201406/8 examples of findmnt command to check mounted file systems on Linux.md
	renamed:    Bash Getopts--Scripts with Command Line Options.md -> 201406/Bash Getopts--Scripts with Command Line Options.md
	renamed:    Collectl--An Advanced All-in-One Performance Monitoring Tool for Linux.md -> 201406/Collectl--An Advanced All-in-One Performance Monitoring Tool for Linux.md
	renamed:    Fix Adobe Flash Player Issue In Chromium In Ubuntu 14.04.md -> 201406/Fix Adobe Flash Player Issue In Chromium In Ubuntu 14.04.md
	renamed:    Guide To Install Ubuntu 14.04 In Dual Boot Mode With Windows 8 Or 8.1 UEFI.md -> 201406/Guide To Install Ubuntu 14.04 In Dual Boot Mode With Windows 8 Or 8.1 UEFI.md
	renamed:    How To Install 'California' Calendar App in Ubuntu 14.04.md -> 201406/How To Install 'California' Calendar App in Ubuntu 14.04.md
	renamed:    How To Remove Drive Icons From Unity Launcher In Ubuntu 14.04 [Beginner Tips].md -> 201406/How To Remove Drive Icons From Unity Launcher In Ubuntu 14.04 [Beginner Tips].md
	renamed:    How to Install Windows 8.1 and Ubuntu 14.04 LTS on the Same Computer.md -> 201406/How to Install Windows 8.1 and Ubuntu 14.04 LTS on the Same Computer.md
	renamed:    How to download webcomics from the command line on Linux.md -> 201406/How to download webcomics from the command line on Linux.md
	renamed:    How to launch applications differently with Gnome-Pie on Linux desktop.md -> 201406/How to launch applications differently with Gnome-Pie on Linux desktop.md
	renamed:    How to manage Linux containers with Docker on Ubuntu.md -> 201406/How to manage Linux containers with Docker on Ubuntu.md
	renamed:    How to manage ip addresses and subnets with phpIPAM.md -> 201406/How to manage ip addresses and subnets with phpIPAM.md
	renamed:    How to manage passwords from the command line on Linux.md -> 201406/How to manage passwords from the command line on Linux.md
	renamed:    How to monitor Nginx web server from the command line in real time.md -> 201406/How to monitor Nginx web server from the command line in real time.md
	renamed:    How to set up a web-based lightweight system monitor on Linux.md -> 201406/How to set up a web-based lightweight system monitor on Linux.md
	renamed:    How to take a screenshot from the command line on Linux.md -> 201406/How to take a screenshot from the command line on Linux.md
	renamed:    How to take full length screenshots of websites via terminal.md -> 201406/How to take full length screenshots of websites via terminal.md
	renamed:    How to use LVM in Linux.md -> 201406/How to use LVM in Linux.md
	renamed:    How to verify DDOS attack with netstat command on Linux Terminal.md -> 201406/How to verify DDOS attack with netstat command on Linux Terminal.md
	renamed:    Install SoundCloud In Ubuntu 14.04.md -> 201406/Install SoundCloud In Ubuntu 14.04.md
	renamed:    Linux Pros' Top Command Line Secrets.md -> 201406/Linux Pros' Top Command Line Secrets.md
	renamed:    Linux Terminal--Dstat monitoring tools.md -> 201406/Linux Terminal--Dstat monitoring tools.md
	renamed:    Making Linux Feel at Home.md -> 201406/Making Linux Feel at Home.md
	renamed:    Open Source's Cult Of Personality Is Dying--Thankfully.md -> 201406/Open Source's Cult Of Personality Is Dying--Thankfully.md
	renamed:    Pros' Secrets and Red Hat 7 and PCLinuxOS 2014.05 Reviews.md -> 201406/Pros' Secrets and Red Hat 7 and PCLinuxOS 2014.05 Reviews.md
	renamed:    Start Practising Linux ip command and Avoid the Habit of Using ifconfig.md -> 201406/Start Practising Linux ip command and Avoid the Habit of Using ifconfig.md
	renamed:    TechView--Linus Torvalds Inventor of Linux.md -> 201406/TechView--Linus Torvalds Inventor of Linux.md
	renamed:    Turn Off Bluetooth By Default In Ubuntu 14.04 [Quick Tip].md -> 201406/Turn Off Bluetooth By Default In Ubuntu 14.04 [Quick Tip].md
	renamed:    Ubuntu Linux Community Manager Jono Bacon Leaves Canonical.md -> 201406/Ubuntu Linux Community Manager Jono Bacon Leaves Canonical.md
	renamed:    What Heartbleed Teaches Us--Be An Open Source Contributor, Not Just A User.md -> 201406/What Heartbleed Teaches Us--Be An Open Source Contributor, Not Just A User.md
	renamed:    Why htop Command Compete Linux top Command.md -> 201406/Why htop Command Compete Linux top Command.md
2014-06-30 21:53:24 +08:00

158 lines
6.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Bash Getopts - 让你的脚本支持命令行参数
================================================================================
以前我总想知道如何为我的Bash脚本创建命令行参数。经过搜索我发现了2个函数可以处理这个问题**getopt** 函数和 **getopts** 函数。我无意争论哪一个函数更好的。**getopts** 是一个shell内建命令而且似乎比 **getopt** 更容易实现这个功能所以在这篇文章里我准备讲讲getopts。
### bash getopts ###
开始的时候,我只试着处理传递给脚本的命令行参数。最后,我添加了另外一些有用的功能函数,使得这个脚本可以成为其他任何交互式脚本处理命令行的开始模板。我还添加了一个纯文本格式的帮助函数,让脚本更加容易阅读。
与其来一长段文字解释 **getopts** 在bash中是如何工作的我认为不如直接来一个能工作的脚本更让人觉得轻松一些。
#!/bin/bash
######################################################################
#This is an example of using getopts in Bash. It also contains some
#other bits of code I find useful.
#Author: Linerd
#Website: http://tuxtweaks.com/
#Copyright 2014
#License: Creative Commons Attribution-ShareAlike 4.0
#http://creativecommons.org/licenses/by-sa/4.0/legalcode
######################################################################
#Set Script Name variable
SCRIPT=`basename ${BASH_SOURCE[0]}`
#Initialize variables to default values.
OPT_A=A
OPT_B=B
OPT_C=C
OPT_D=D
#Set fonts for Help.[译注: 这里tput用来更改终端文本属性,比如加粗,高亮等]
NORM=`tput sgr0`
BOLD=`tput bold`
REV=`tput smso`
#Help function
function HELP {
echo -e \\n"Help documentation for ${BOLD}${SCRIPT}.${NORM}"\\n
echo -e "${REV}Basic usage:${NORM} ${BOLD}$SCRIPT file.ext${NORM}"\\n
echo "Command line switches are optional. The following switches are recognized."
echo "${REV}-a${NORM} --Sets the value for option ${BOLD}a${NORM}. Default is ${BOLD}A${NORM}."
echo "${REV}-b${NORM} --Sets the value for option ${BOLD}b${NORM}. Default is ${BOLD}B${NORM}."
echo "${REV}-c${NORM} --Sets the value for option ${BOLD}c${NORM}. Default is ${BOLD}C${NORM}."
echo "${REV}-d${NORM} --Sets the value for option ${BOLD}d${NORM}. Default is ${BOLD}D${NORM}."
echo -e "${REV}-h${NORM} --Displays this help message. No further functions are performed."\\n
echo -e "Example: ${BOLD}$SCRIPT -a foo -b man -c chu -d bar file.ext${NORM}"\\n
exit 1
}
#Check the number of arguments. If none are passed, print help and exit.
NUMARGS=$#
echo -e \\n"Number of arguments: $NUMARGS"
if [ $NUMARGS -eq 0 ]; then
HELP
fi
### Start getopts code ###
#Parse command line flags
#如果选项需要后跟参数,在选项后面加":"
#注意"-h"选项后面没有":",因为他不需要参数。选项字符串最开始的":"是用来去掉来自getopts本身的报错的同时获取不能识别的选项。译注如果选项字符串不以":"开头发生错误非法的选项或者缺少参数getopts会向错误输出打印错误信息如果以":"开头,则不会打印[在man中叫slient error reporting]同时将出错的选项赋给OPTARG变量
while getopts :a:b:c:d:h FLAG; do
case $FLAG in
a) #set option "a"
OPT_A=$OPTARG
echo "-a used: $OPTARG"
echo "OPT_A = $OPT_A"
;;
b) #set option "b"
OPT_B=$OPTARG
echo "-b used: $OPTARG"
echo "OPT_B = $OPT_B"
;;
c) #set option "c"
OPT_C=$OPTARG
echo "-c used: $OPTARG"
echo "OPT_C = $OPT_C"
;;
d) #set option "d"
OPT_D=$OPTARG
echo "-d used: $OPTARG"
echo "OPT_D = $OPT_D"
;;
h) #show help
HELP
;;
\?) #unrecognized option - show help
echo -e \\n"Option -${BOLD}$OPTARG${NORM} not allowed."
HELP
#在这里如果你不想打印完整的帮助信息,只想显示简单的错误信息,去掉上面的两行,同时使用下面的两行。
#echo -e "Use ${BOLD}$SCRIPT -h${NORM} to see the help documentation."\\n
#exit 2
;;
esac
done
shift $((OPTIND-1)) #This tells getopts to move on to the next argument.
### End getopts code ###
### Main loop to process files ###
#这里你可以用你的脚本处理逻辑来替代。这个例子只是在终端中打印文件的文件名和后缀名。你可以把任意其他的文件处理任务放到这个while-do循环中。
while [ $# -ne 0 ]; do
FILE=$1
TEMPFILE=`basename $FILE`
#TEMPFILE="${FILE##*/}" #另外一种获取不带后缀的文件名的方法
FILE_BASE=`echo "${TEMPFILE%.*}"` #file without extension
FILE_EXT="${TEMPFILE##*.}" #file extension
echo -e \\n"Input file is: $FILE"
echo "File withouth extension is: $FILE_BASE"
echo -e "File extension is: $FILE_EXT"\\n
shift #Move on to next input file.
done
### End main loop ###
exit 0
将上面的代码复制到你的文本编辑器里,然后保存到你的可执行路径下。我将这个脚本命名为 **options** 并保存到 **/home/linerd/bin** 路径下。保存之后记得给你的脚本添加可执行权限。
chmod +x ~/bin/options
现在脚本已经可以运行了。试试用 **-h** 参数来打印帮助信息吧。
options -h
遇到不支持的选项,脚本同样可以给出提示,并打印帮助信息。
options -z
最后getopts可以以任意的顺序处理你给的命令行参数。唯一的限制是你要处理的文件必须放在所有参数的最后。
options -d bar -c chu -b man -a foo example1.txt example2.txt
现在你可以从这些例子里看到如何通过命令行参数给脚本里的变量赋值。这个脚本里除了getopts还有很多其他的东西但是我认为这些就足以成为一个新脚本的开头模板了。如果你有兴趣更深入地学习bash的getopts你可以找找深埋在man page的“Builtins”这一节里的文档也可以从 [Bash Reference Manual][1] 找到信息。
### 接下来呢? ###
你会用getops来干什么呢在评论里告诉我吧。
--------------------------------------------------------------------------------
via: http://tuxtweaks.com/2014/05/bash-getopts/
译者: CNprober \<travelwithheart@yeah.net, QQ619913541\> 校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[1]:http://tuxtweaks.com/2014/05/bash-getopts/www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html