[Shell] using getopts in functions

Source: Internet
Author: User
[Shell] before using getopts in a function. bashrc has written a function that uses getopts, but it is strange that after this function is called once, the parameter cannot be parsed again and then queried, the OPTIND variable is detected. The original code is as follows: www.2cto. c... [shell] before using getopts in a function. bashrc has written a function that uses getopts, but it is strange that after this function is called once, the parameter cannot be parsed again and then queried, the error is caused by the OPTIND variable. The original code is as follows: www.2cto.com 01 function stjob () {02 # unset OPTIND 03 while getopts ": rsd" opt; do04 case $ opt in05 r) echo $ opt; 06 s) echo $ opt; 07 d) echo $ opt; 08 \? ) Echo "Usage stjob-d-s-r" 09 return; 10 esac11 done12} the cause of the problem is that after the first call, the OPTIND value is saved in the current session, getopts parses parameters based on OPTIND, because the OPTIND has a value when it calls the stjob for the second time, causing the parsing to be abnormal. Therefore, to ensure normal resolution, you should set OPTIND to zero or remove this variable before parsing.

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.