bash - getopts in switch case - bash

I'm trying to use getopts inside a switch case loop.
if i use only getopts or only the switch case it's work, however when i combine those two the getopts dos not trigger.
i have search a lot but i cat fins any mention for how to combine them, and problem i missing something stupid so for give me ...
here is the code essence.
#!/bin/bash
case $1 in
ver)
echo "vesion"
exit 0
;;
op)
while getopts ":a" opt; do
case $opt in
a)
echo "-a was triggered!" >&2
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done
;;
esac
when i do that
# bash -x test.sh op -a
i get
+ case $1 in
+ getopts :a opt
(and without debug i get nothing)
what is that that i missing to combine these two
Thanks :)

You should add a shift instruction at the beginning of your op) choice, before the call to getopts, to eat the op argument itself. Else, the first argument that getopts will analyze is op and it will silently stop (end of options).

Related

How to getopts after $1 in bash [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to run the script as ./script speed -a some_value -b some_value also ./script accuracy -a some_value -b some_value
What I tried is
while [ -n "$1" ]; do
case "$1" in
speed)
for i in "${#:2}"
do while getopts "a:b:" opt; do
case "${opt}" in
a) list=$OPTARG
echo $list
;;
b) list2=$OPTARG
echo $list2
;;
esac
done
done
echo "speed option passed"
break ;;
accuracy) echo "similar to above function"
break ;;
*) echo "Option $1 not recognized" ;; # In case you typed a different option other than a,b,c
esac
shift
done
getting output as when ran ./script speed -a some_value
this is something
speed option passed
I don't know if this is possible or not or is there any way to do something like this?
I don't think you want the outer loop (while [ -n "$1" ]; do), unless you want to be able to process multiple subcommands in a single run. That is, do you want this:
./script speed -a some_value -b some_value accuracy -a some_value -b some_value
To be roughly equivalent to this:
./script speed -a some_value -b some_value
./script accuracy -a some_value -b some_value
If not, remove that loop because you'll only be processing one subcommand per run. If you do want to process more than one subcommand per run, then you need to take some extra steps to remove or skip over the arguments relating to one subcommand before running the next one.
You do want to remove the for i in "${#:2}" loop -- that just doesn't mix with the way getopts works. What you do need to do is skip over the subcommand name before processing the options. You could either use shift to remove the subcommand name, something like this:
case "$1" in
speed)
shift # Remove the first argument ("speed")
while getopts "a:b:" opt; do
...
If you're going to allow multiple subcommands, add shift $((OPTIND-1)) sfter the getopts loop, to get it ready for the next subcommand.
Or you could modify OPTIND to tell getopts that it's already processed the first argument and it can go to work on the second:
case "$1" in
speed)
OPTIND=2 # Tell getopts to start processing at arg #2
while getopts "a:b:" opt; do
...
If you're going to handle multiple subcommands with this method... well, it's a bit more complicated and I think I'll duck the question.
Yet another option is to put the code for each subcommand in a function, and call it with all but the first argument:
speed_subcommand() {
local OPTIND
while getopts "a:b:" opt; do
...
}
case "$1" in
speed)
speed_subcommand "${#:2}" ;;
accuracy)
accuracy_subcommand "${#:2}" ;;
...
This method doesn't really mix with handling multiple subcommands per run.

How do I make an option accept an arbitrary number of arguments

I am trying to write a shell script with options that take different numbers of values in each run, e.g.
Run 1:
./myscript --input <file1> <file2> --output <folder1>
Run 2:
./myscript --input <file1> <file2> <file3> --output <folder1> <folder2>
I tried using getopts as follows:
while getopts ":i:o:" opt; do
case $opt in
i)
echo "treatment files are: $OPTARG" >&2
infiles="${OPTARG}"
;;
o)
echo "control files are: $OPTARG" >&2
outdir="${OPTARG}"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
However, the only way I found to input variable amounts of values for the "-i" option is by quotation ("file1 file2"), which prevents me/the user to use the autocomplete function of the command line to help generating the file path. Also this option does not seem allow me to use "--input" syntax to pass the options.
Anybody can help?
Thanks a lot.
You have two questions here. One of them is "how do I implement long options in my shell script?", for which there is good reading here.
The other question is, "how do I make an option accept an arbitrary number of arguments?" The answer there is, mostly, "you don't". Often the cleanest solution is to have your script accept the option multiple times, as in:
./myscript -i <file1> -i <file2> -i <file3>
This is relatively easy to handle by appending to a Bash array, as in:
infiles=()
while getopts ":i:o:" opt; do
case $opt in
i)
infiles+=("${OPTARG}")
;;
esac
done
And later on you can iterate over those values:
for inputfile in "${infiles[#]}"; do
...
done
Read about bash arrays for more information.
If you don't like that solution, you could implement your own option parsing in a manner similar to some of the answers to the question to which I linked in the first paragraph. That would allow you to get the command line semantics you want, although I would argue that behavior is at odds with the way a typical program behaves.

Issue with getops parameter

Currently, I'm working on a bash script that is meant to have parameters passed through it.
My getOps lines:
while getopts ":s:d:e:*" opt; do
case $opt in
s)
kb_status
;;
d)
kb_disable
;;
e)
kb_enable
;;
*)
echo "Invalid option: -$OPTARG"
;;
esac
done
The main issue is whenever I try to pass the script through
./myscript.sh -e`
I get the following message from my wildcard parameter:
Invalid option: -e
However, when I run it as
./myscript.sh -ee
or have any second letter in the parameter, it passes perfectly fine. Can someone help me fix this issue?
The problem is the ":" character after the e in
while getopts ":s:d:e:*" opt; do
The ":" tells getopts to expect an argument after the -e option.
So if you want your script to just support -s -d and -e options, then do the following:
while getopts sde opt; do
Putting : after e in the option list means that the -e option requires an argument. -e by itself is missing the argument, -ee sets the value of the argument to e.
Since you don't do anything with $OPTARG, it looks like you don't really require arguments to your options, so you shouldn't be using : after each of them.
while getopts ":sde*" opt; do
It's also unclear why you have * at the end of the option list. That will allow "-*", but the case block will report that as an error.

Using getopts with a switchless path

I am trying to write a short script, utilizing getopts. I want it to take optional switches, or just run as the default. I have a -d switch to enable debugging, and I'd like every other argument to be a path. The ideal command line looks as such, with paths being optional, and theoretically limitless:
$0 [-d] [/path1[ /path2[ ...]]]
I am currently using getopts as such below:
while getopts ":d" opt; do
case $opt in
d)
DEBUG=true
;;
h)
echo USAGE: $0 \[-d\] \[\/mount\/point\/1 ...\]
exit 0
;;
\?)
echo Incorrect syntax
;;
esac
done
What can I put in the while getopts section, and in the case set, to allow paths to be entered, as many as needed?
You don't need anything in the loop or getopts call for that. getopts stops at the first non-option.
After your loop all your paths will still be in positional arguments available for use.
Also you don't have h in your getopts string so it isn't valid.

How to use getopts with unix shell functions?

The getopts command doesn't seem to work in a function. Maybe I did something wrong. The code below is what I have now. it is working if I put the whole while loop outside function. I am wondering if there is a way to make getopts work with functions ? I am new to the shell script. Any help would be appreciated :)
getOptions()
{
while getopts :al:f:vd opt; do
case "$opt" in
l) logFile = $OPTARG ;;
f) fileTable = $OPTARG ;;
v) verbose = 1 ;;
d) set -x ;;
a) echo "a";;
\?) echo "Invalid option: -$opt";;
esac
done
shift $(($OPTIND - 1))
}
One reason might be your usage of things like logFile = $OPTARG when you shouldn't have any spaces there (it should read logFile=$OPTARG).
Another reason is the fact that $1, $2, etc. are all referring to the function's arguments, not the shell script's arguments. Since the shell works that way, and getopts uses $1, $2, etc., you're using the function's arguments with getopts, not the script's arguments. In other words, confining your option processing to a shell function is not a good idea.

Resources