DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • A Guide to Serverless Node.js Functions Using Google Cloud
  • Emulating the History Command Within a Bash Script
  • Mainframe Development for the "No Mainframe" Generation
  • When Scrum Feels Like Dressing for Dinner

Trending

  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise

Bash: Parse Options And Non-Options With Getopts

By 
Jakub Holý user avatar
Jakub Holý
·
Jan. 10, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
12.4K Views

Join the DZone community and get the full member experience.

Join For Free

Parsing script or function options and non-option arguments is easy in Bash with getopts but there are some catches, such as the need to reset OPTIND. We will se how to do it using getopts, shift, and case.

The code below will parse the function arguments and remove them so that $1 will refer to the first non-option argument (i.e. not starting with -). You would invoke it f.ex. as latest_recur -x Hello -a '*.txt'.

# Find the latest files under the current dir, recursively; options:
# -a list all, not only 30 latest
#  - pattern passed to find's -name; ex.: "*.log.processed"
function latest_recur {
   local show_all=
   OPTIND=1
   while getopts "ax:" opt; do
      case $opt in
         a) show_all=yes ;;
         x) echo "You said: $OPTARG" ;;
         \?) echo "Invalid option: -$OPTARG" >&2; return 1;;
     esac
   done
   shift $((OPTIND-1))

   if [ -z "$1" ]; then NAME_ARG=""; else NAME_ARG="-name $1"; fi
   find -type f $NAME_ARG | xargs --no-run-if-empty stat --format '%Y :%y %n' | sort -nr | if [ -z "$show_all" ]; then head -n 30 -; else cat -; fi
}

  • #5, #9 the variable used to store the flag must be defined/reset first
  • #6 OPTIND is a global variable pointing to the next argument that getopts should parse; you must reset it manually (otherwise the next call to the function will ignore its arguments)
  • #7 getopts parses one by one all the supported options (a, x here) and stores them into $opt;
  • #14 we must manually shift away the processed option arguments so that the first non-option argument (‘*.txt’) will become argument number 1 as you can see at #16; OPTIND is set by getopts

Getopts can do quite a lot. It supports short options with or without arguments such as “-lht”, “-l -h -t”, “-l -I ‘*.swp’”. It can also report/ignore unknown arguments etc., see its brief documentation and this small getopts tutorial. Briefly said, getopts takes opstring and varname; opstring is a list of letters optionally followed by ‘:’ to indicate that that flag requires a value; varname is the name of the variable to store the flag name into. If you put : in front of the opstring (“:ax:”) then it will not complain about unknown options or missing arguments for options that require them.


Bash (Unix shell)

Published at DZone with permission of Jakub Holý, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Guide to Serverless Node.js Functions Using Google Cloud
  • Emulating the History Command Within a Bash Script
  • Mainframe Development for the "No Mainframe" Generation
  • When Scrum Feels Like Dressing for Dinner

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: