Bash: using getops for this specific use - linux

I would need my bash scrip to work either with:
No arguments
./script.sh
Path argument (classic argument, will saved as var to var=$1)
./script.sh /root/home/dir/
With switch -a (with it's own argument)
./script.sh -a picture.jpeg
Or both combined
./script.sh -a picture.jpeg /root/home/dir/
I have something like this:
while getopts ":a:" opt; do
case $opt in
a)
I_ARGUMENT=$OPTARG
echo "A ARGUMENT IS: $OPTARG"
;;
:)
echo "-a requires argument"
;;
esac
done
And then something like this for the path argument:
if [ -z "$1" ]
then
:
else
PATH="$1"
fi
Which obviously doesn't work well (at all) together. Could you help me to combine this two things? Thank you.

How about something like this
pathToHomeSlashDir=~/dir/ #default value will be home/dir/
if [ $# -gt 0 ]
then
while [ $# -gt 0 ]
do
case "$1" in
-a)
if [ $# -gt 1 ]
then
image="$2"
shift
else
echo "Please insert -a argument"
exit
fi
;;
*)
pathToHomeSlashDir="$1"
;;
esac
shift
done
fi
You'd just need to handle the variables then

Related

bash script options parser fails

I have a bashscript.sh that I $ chmod +x bashscript.sh and move it to $ mv bashscript.sh ~/.local/bin/ in order for it to be executable like a system command.
I'd like to be able to invoke it with
bashscript [<-w|-working|--working>[=|:]] <y|yes|n|no>
And return usage/help/error (call it whatever we want) if the call isn't respected.
To do so, I wrote this parsing part:
usage(){
echo "you're wrong."
exit 1
}
[[ $# -lt 1 ]] && usage
options=$(getopt -o y,n,h,w: -l yes,no,help,working: -- "$#")
set -- $options
while true; do
case "$1" in
-h|--help|*) usage
shift;;
y|yes)
#do something
shift;;
n|no)
#..
shift;;
-w|-working|--working)
shift;;
--) #this is just syntax
shift
break;;
esac
done
But when I test it doesn't work as intended*, would you know why/have a sample that handles my option possibilites?
*edit : I always trigger the usage display
edit 2 : removed the spaces around the "=" of options as #costaparas3 pointed out, thank you, still stuck to usage() though
Here are the issues I found:
Exit if there are no arguments
Set the options with options=$(... (no spaces)
-h|--help|*) matches everything so you have an infinite loop. You don't need to match on * as getopt will reuturn non-zero if it finds an invalid argument, and the match on -- is what usually terminates the loop.
getopt returns non-zero for invalid arguments so exit 1 then
Use -n|--no to specify short and long options
--working requires an argument but you only shift 1.
-working is not valid (with getopt). Use either -w or --working.
Here is corrected version:
#!/bin/bash
usage() {
echo "you're wrong."
exit $1
}
[ $# -lt 1 ] && usage
options=$(getopt -o y,n,h,w: -l yes,no,help,working: -- "$#")
[ $? -ne 0 ] && usage 1
# default values
yes=
working=
set -- $options
while :
do
case "$1" in
-h|--help)
usage
;;
-y|--yes)
yes=1
shift
;;
-n|--no)
yes=0 # or no=1
shift
;;
-w|--working)
working=$2
shift 2
;;
--)
break
;;
esac
done

not allow multiple option in getopts of bash script

Having bash script as follows
#! /bin/bash
usage()
{
echo -e "need help!"
}
while getopts ":a:b:h" OPTION
do
case $OPTION in
a)
printf "a option with value %s\n" $OPTARG
;;
b)
printf "b option with value %s\n" $OPTARG
;;
h)
usage
;;
?)
echo -e "No option selected"
;;
esac
done
exit 0
Above script run fine with different option but i wanted to extend it to not allow to pass multiple option at same time like as following argument
$ ./test.bash -a 1 -b 2
a option with value 1
b option with value 2
should be not valid means some way it give me error like wrong syntax i achieved it by as follows but it seems to long it is as follow
#! /bin/bash
usage()
{
echo -e "need help!"
}
let "a_count=0"
let "b_count=0"
MY_ARG=""
while getopts ":a:b:h" OPTION
do
case $OPTION in
a)
let a_count=1
MY_ARG=$OPTARG
;;
b)
let b_count=1
MY_ARG=$OPTARG
;;
h)
usage
;;
?)
echo -e "No option selected"
;;
esac
done
[[ $a_count -eq 1 ]] && [[ $b_count -eq 1 ]] && echo "wrong command sytax" && exit 0
[[ $a_count -eq 1 ]] && printf "a option with value %s\n" $MY_ARG
[[ $b_count -eq 1 ]] && printf "b option with value %s\n" $MY_ARG
exit 0
run like
$ ./test.bash -a 1 -b 2
wrong command sytax
But i want to finish validation in while..loop of getopts. Also this validation not works for following command
./test.bash -a -b
a option with value -b
any one have batter idea how to use getopts for this type validation?
you've almost got it. The : after the a and after the b say that they take an argument, so your example with -a -b is actually valid, saying "There is option a with value -b".
If you really just want "-a or -b and then an argument", you probably don't need getopts at all, but should do:
[ "$1" == "-a" ] && printf "a option with value %s\n" $2
[ "$1" == "-b" ] && printf "b option with value %s\n" $2
any one have batter idea how to use getopts for this type validation?
well, actually, you're explicitly telling geptopts that -a and -b are not boolean parameters, but parameters that take an extra argument. The argument parser cannot tell whether the argument following -a is a parameter or its own argument, and thus they consider [-a ] [-b ] as syntax.
The best way, would actually be to have a different boolean parameter that matches the use case when you do not want an argument for -a and -b.
Though, it won't help you with your issue trying to have parameters with argument or boolean, but for the argument syntax checking you can try docopt which has a nicer way to create command line interface. You focus on doing the --help documentation, it parses it to build your parameter/argument parser. e.g.:
eval "$(docopts -V - -h - : "$#" <<EOF
Usage: myscript [(-a <foo> | -b <bar> | -abool | -bbool)]
-a <foo> The A option.
-b <bar> The B option.
-abool The A bool
-bbool The B bool
--help Show help options.
--version Print program version.
----
myscript 0.0.0
Copyright (C)20.. Your Name
License...
)"
if $a ; then
echo "a option! with $a"
fi
if $b ; then
echo "b option! with $b"
fi
if $abool ; then
echo "abool option!"
fi
if $bbool ; then
echo "bbool option!"
fi
This is not quite perfect because it will always process the first switch, but it does place an exit inside the while loop which is in keeping with your design requirement. It may give you an idea how to finish it.
#!/bin/bash
usage()
{
echo -e "need help!"
}
while getopts "a:b:h" OPTION
do
case $OPTION in
a)
aflag=1
aval=$OPTARG
if [ ! -z "$bflag" ]
then
printf "ERROR: cant use both -a and -b\n"
exit 1
fi
;;
b)
bflag=1
bval=$OPTARG
if [ ! -z "$aflag" ]
then
printf "ERROR: cant use both -a and -b\n"
exit 1
fi
;;
h) usage ;;
?) printf "ERROR" ; exit 1 ;;
esac
done
if [ ! -z "$aflag" ]
then
printf "a option with value %s $aval\n"
elif [ ! -z "$bflag" ]
then
printf "b option with value %s $bval\n"
fi
exit 0
If you still want to use the getopts I would use bash built-in variable for the arguments count $# to detect wrong number of arguments passed:
#! /bin/bash
usage()
{
echo -e "need help!"
}
# Check if number of arguments is greater than 2 as "-a1" (one arg) and "-a 2" are correct.
# You might want to check for other wrong inputs.
if [ $# > 2 ]
then
echo "Some warning t o the user or"
usage
exit 1
fi
while getopts ":a:b:h" OPTION
do
case $OPTION in
a)
printf "a option with value %s\n" $OPTARG
;;
b)
printf "b option with value %s\n" $OPTARG
;;
h)
usage
;;
?)
echo -e "No option selected"
;;
esac
done
exit 0

Bash multiple combinations in getopts

I would like to make a script where you can give a couple of parameters with it:
while getopts ":a:b:c:" opt; do
case $opt in
a)
echo "-a was triggered
;;
b)
echo "-b was triggered
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
The code I have now works but the problem I have is that I want to give another function/echo if it combines.
Example:
When I do: .MyScript -ab than it should give another function that what is defined in "a" or in "b"
so a bit like:
ab) -> Script -a -b or Script -ab
echo "-ab was triggered"
What is the best solution to do this?
Any ideas, your free to post!
while getopts ":a:b:c:" opt; do
case $opt in
a)
echo "-a was triggered"
a_val=$OPTARG
;;
b)
echo "-b was triggered"
b_val=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
if [[ -n $a_val ]]; then do something with "$a_val"; fi
if [[ -n $b_val ]]; then do something with "$b_val"; fi
The only situation this may cause confusion is if the user passes -a "" -- one workaround is:
a=false
b=false
while getopts ":a:b:c:" opt; do
case $opt in
a) echo "-a was triggered"; a_val=$OPTARG; a=true ;;
b) echo "-b was triggered"; b_val=$OPTARG; b=true ;;
esac
done
if $a; then do something with "$a_val"; fi
if $b; then do something with "$b_val"; fi
Here, there are no brackets: if $a; then ... because I'm invoking the command "true" or "false" and acting on that exit status.
UPDATED
You can use the getopt(1) linux utility. This is not a bash internal function, but this can handle long arguments.
Try this:
declare -A OPTARG
GetOpt() {
local prog="${BASH_SOURCE[0]}"
[ $# -eq 0 ] && echo "$prog: Bad call of GetOpts">&2 && exit 1
local longopt="$1"
shift
local tmp
tmp=$(getopt -n"$prog" -a -l "$longopt" -- '' "$#") || exit
eval "tmp=($tmp)"
local i
for((i=0;i<${#tmp[*]};++i)){
key=${tmp[i]#--}
[ -z "$key" ] && break
if [[ "${tmp[i+1]}" =~ ^-- ]]; then OPTARG[$key]=1
else OPTARG[$key]="${tmp[++i]}"
fi
}
for((j=0;++i<${#tmp[*]};++j)){ OPTFILE[j]=${tmp[i]};}
}
GetOpt "a b ab file:" "$#"
[ "${OPTARG[a]}" -a "${OPTARG[b]}" ] && OPTARG[ab]=1 && unset OPTARG[a] OPTARG[b]
[ "${OPTARG[a]}" ] && echo Do a
[ "${OPTARG[b]}" ] && echo Do b
[ "${OPTARG[ab]}" ] && echo Do ab
The defined GetOpt function will place the parsed command line argument with the checked long options to the associative array called OPTARG. If there is an error it will fail informing about the problem.
With getopt's -a option you can use -ab or --ab format. Keep in mind that if You have del defined, then the -d option (if -d is not specified) will expand to --del.
If You specify an arg with additional option it can contain spaces. E.g. if -l file: defined in getopt then it can be used as ./test --file="q w". ${OPTARG[file]} will be q w.
The OPTFILE array contains the optional arguments (args given after --).

Setting variable to last arg from command line parameters

I'm trying to write a script in a way that makes it simple to add future command line args. I'm using getopts and that works well. However, I'm running into issues with the case statement.
args=`getopt lLo:t: $*`
if [ $? -ne 0 ]
then
echo "Usage: Default error message"
fi
while [ "$#" -eq 3 ] || [ "$#" -eq 5 ]
do
if [ "$1" != "-o" ] && [ "$1" != "-t" ]
then
echo "\nInvalid argument sequence."
exit 1
fi
case "$1" in
(-o)
shift
VAR1="$1"
shift
;;
(-t)
shift
VAR2="$1"
shift
;;
(*)
LAST_VAR="$1"
;;
(--) shift; break;;
esac
done
If I then echo $LAST_VAR it is null. Any ideas? Is there a better way to do this?
Some findings:
You need spaces around each [ and ] (line 2). See help [.
You don't need ( in case matchings. See help case.
You can use VAR1="$2" and shift 2 instead of two separate shifts. See help shift.
You want to put the -- case before *, and move the break to the * case.
Follow the logic backwards: LAST_VAR will be set if $1 is neither -o nor -t. Before that you exit if $1 is neither -o nor -t. So LAST_VAR can never be set.
I would suggest looking at some getopt examples for some ideas. Shameless plug for some tested code:
# Process parameters
params="$(getopt -o d:e:fshv \
-l diff:,exclude:,force,skip-existing,help,verbose \
--name "$cmdname" -- "$#")"
if [ $? -ne 0 ]
then
usage
fi
eval set -- "$params"
unset params
while true
do
case $1 in
-d|--diff)
diff_exec=(${2-})
shift 2
;;
-e|--exclude)
# Will override $default_excludes
excludes+=("${2-}")
shift 2
;;
-f|--force)
action='R'
shift
;;
-s|--skip-existing)
action='S'
shift
;;
-h|--help)
usage
exit
;;
-v|--verbose)
verbose='--verbose'
shift
;;
--)
shift
if [ -z "${1:-}" ]
then
error "Missing targets." "$help_info" $EX_USAGE
fi
if [ -z "${2:-}" ]
then
error "Missing directory." "$help_info" $EX_USAGE
fi
targets=(${#:1:$(($#-1))})
source_dir="${#:$#}"
break
;;
*)
usage
;;
esac
done

Shell getopts for grabbing arguments

I have a script which should be run as either one of these two:
script.sh -t TYPE
script.sh -t TYPE -f FILE
If it is run without a -t flag I want it to error and exit.
If it is run with a -t flag I want to grab the value and store it in a
variable called "$TYPE" and print "JUST $TYPE"
If it is run with a -f flag I want it grab the value and store it in a variable called
"$FILE" and print "$TYPE and $FILE"
From information and tutorials on both here and the internet generally this is the closest I can get. Can anyone help me put in the second conditional into this existing code?
while getopts ":t:" opt; do
case $opt in
a)
echo "JUST $OPTARG" >&2
;;
\?)
echo "Error - Invalid type argument" >&2
exit 1
;;
:)
echo "Error - No type argument" >&2
exit 1
;;
esac
done
I think you get confused how you should handle command line arguments.
The common way is that the processing of all arguments precedes the actual job of the program/script.
Further more (related to getopts) if an option is appended by a colon, that indicates that the option is expected to have an argument.
Your case statement looks overpopulated too. You don't need to test for a colon and a question mark. The whole testing can be put after the while loop
I would do it like this
#!/bin/bash
unset TYPE
unset FILE
#uncomment if you want getopts to be silent
#OPTERR=0
while getopts "t:f:" opt; do
case $opt in
t)
TYPE=$OPTARG
echo "JUST $OPTARG"
;;
f)
FILE=$OPTARG
;;
esac
done
if ! test "$TYPE" ; then
echo "-t is obligatory"
exit 1
fi
if test "$TYPE" && test "$FILE" ; then
echo "$TYPE and $FILE"
fi
Have a look at this:
TYPE=""
FILE=""
while getopts "t:f:" opt; do
case $opt in
t) TYPE="$OPTARG"
;;
f) FILE="$OPTARG"
;;
esac
done
if [ -z "$TYPE" ]; then
echo "No -t. Bye."
exit 1 # error
else
if [ -n "$FILE" ]; then
echo "$TYPE and $FILE"
else
echo JUST $TYPE
fi
fi

Resources