I am looking for a reusable code snippet that checks for a command line argument for bash.
Ideally, something similar to the functionality offered by the Apache Commons CLI:
Commons CLI supports various types of parameters:
- POSIX-like options (e.g. tar -zxvf foo.tar.gz)
- GNU as long parameters (i.e. du --human-readable --max-depth = 1)
- Short options with a value (gcc -O2 foo.c)
- long options with one def (i.e. ant -projecthelp)
- ...
and automatically generates a usage message for the program, for example:
usage: ls -A,--almost-all do not list implied . and .. -a,--all do not hide entries starting with . -B,--ignore-backups do not list implied entried ending with ~ -b,--escape print octal escapes for nongraphic characters --block-size <SIZE> use SIZE-byte blocks -c with -lt: sort by, and show, ctime (time of last modification of file status information) with -l:show ctime and sort by name otherwise: sort by ctime -C list entries by columns
I would include this piece of code at the beginning of my Bash scripts and reuse it in the scripts.
There must be something like this. I donโt think we are all writing code with this effect or similar:
#!/bin/bash NUMBER_OF_REQUIRED_COMMAND_LINE_ARGUMENTS=3 number_of_supplied_command_line_arguments=$# function show_command_usage() { echo usage: (...) } if (( number_of_supplied_command_line_arguments < NUMBER_OF_REQUIRED_COMMAND_LINE_ARGUMENTS )); then show_command_usage exit fi ...
source share