Getopts parsing command line parameters for unixshell learning

Source: Internet
Author: User
The getopts parsing command line parameter getopts command is built in shell. you can get the valid command line parameters specified by a single character. each character has a & amp; lsquo; -& amp; rsquo; No. or & amp; lsquo; + & amp; rsquo; No. To put it simply, for example, run the command: iptabl unix shell to learn the getopts parsing command line parameter getopts command is built-in in shell, you can get the valid command line parameter specified by a single character, A single character has a '-' or '+. To put it simply, run the following command: iptables-t nat-a postrouting-p tcp-o eth0-s 192.168.2.0/24-j SNAT -- to public_ip it implements the function of converting an intranet ip address to A public ip address to access the Internet, however, how can we parse so many parameters? getopts is to parse such parameters. Therefore, getopts is a very practical tool. it helps you easily parse command line parameters when you write scripts. but how does it parse it, if the script provides the command line parameter-s 5-m 10-d 2-p my_shell, use getopts: s: m: h: d: p indicates that if ":" is added before each switch for the specified item s, m, d, and p, a parameter is required for this toggle. For details, see the code my_shell.sh. it implements the function of converting all parameters such as daily hours, minutes, and seconds to seconds: click (here) fold or open SECS = 0 MINUTES = 0 HOURS = 0 DAYS = 0 PROCESS = 0 while getopts: s: m: h: d: p TIMED 2>/dev/NullDC case $ TIMED in s) SECS = $ OPTARG; m) (MINUTES = $ OPTARG * 60); h) (HOURS = $ OPTARG * 3600); d) (DAYS = $ OPTARG * 86400); p) PROCESS = $ OPTARG ;;\?) Usage exit; esacdone (TOTALSECS = $ SECS + $ MINUTES + $ HOURS + $ DAYS) echo "total seconds: $ TOTALSECS" run the command at this time: bash my_shell.sh-s 20-m 3-h 5-d 8-p my_shell, you can see the result of parsing parameters after running the command.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.