Bash logic combination to restrict a user to the required number of argument
Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Bash logic combination to restrict a user to the required number of argument
My bash function is suppose to ask for an argument when it is not supplied and indicate surplus argument when the argument supplied is more than two (2). But presently,when i supply it with 3 argument it does not echo "surplus argument" but give the same result with when i supply one or two argument. Please how do i correct this or is it from my bash logic combination?
below is the code:
Last edited by dan-german; 12-18-2019 at 11:35 PM.
Reason: i am modifying the question and also the elif statement because i noticed an error on my part
Distribution: openSUSE, Raspbian, Slackware. Previous: MacOS, Red Hat, Coherent, Consensys SVR4.2, Tru64, Solaris
Posts: 2,803
Rep:
Quote:
Originally Posted by dan-german
My bash function is suppose to ask for an argument when it is not supplied and indicate surplus argument when the argument supplied is more than three (3). But presently,when i supply it with 3 argument it does not echo "surplus argument" but give the same result with when i supply one or two argument. Please how do i correct this or is it from my bash logic combination?
below is the code:
Q: What are trying to accomplish with this script? Comments in code are always helpful.
Rather than an obtuse combination of if-elif-fi statements, I'd go with something like:
Code:
#!/bin/bash
case $# in
0)
echo -e "VAR1? \c"; read VAR1
echo -e "VAR2? \c"; read VAR2
;;
1 | 2)
echo "This is OK"
VAR1=$1
VAR2=$2
;;
*)
echo "TMI... Ignoring it."
esac
echo "Proceeding with \"${VAR1}"\" and \"${VAR2}\"..."
Aside: You might want to consider abandoning positional parameters. Take a look at the getopt(1) utility to parse command line parameters (bash itself include a built-in function, 'getopts', that does something similar but I find getopt(1) easier to use. YMMV). Here's an example of its use:
Code:
#!/bin/bash
#
# This script is an example of how to use getopt(1) to parse command line
# switches and extract any arguments.
#
function usage() {
echo "Usage: myscript --in=input-file --out=output-file [--debug] [--help]" 1>&2
exit 1
}
#
# Use getopt(1) to help parse command line options. Note: If no short options
# are going to be used, "--options '' " should be specified to prevent the
# first long option from being misinterpreted as an argument to "--options"
# and being lost.
#
MYSCRIPT_OPTS=$( getopt --options '-d,-h,-i:,-o:' --longoptions 'debug,help,in:,out:' -n 'myscript' -- "$@" )
if [ $? != 0 ]; then
echo "Failed parsing options." >&2
usage
else
eval set -- "${MYSCRIPT_OPTS}"
DEBUG=FALSE
IN="undefined"
OUT="undefined"
while true; do
case "$1" in
--debug ) DEBUG=TRUE; shift ;;
--help ) usage; exit ;;
--in ) IN="$2"; shift 2 ;;
--out ) OUT="$2"; shift 2 ;;
-- ) shift; break ;;
* ) break ;;
esac
done
fi
[ ${DEBUG} == "TRUE" ] && echo "DEBUG is enabled"
echo IN=$IN
echo OUT=$OUT
echo "Now we do something with those command line options..."
exit
You can be pretty flexible in how you supply information to the script:
Code:
$ ./bash--getopt_example -h
Usage: myscript --in=input-file --out=output-file [--debug] [--help]
$ ./bash--getopt_example --help
Usage: myscript --in=input-file --out=output-file [--debug] [--help]
$ ./bash--getopt_example -i input.txt --o=output.txt -d
DEBUG is enabled
IN=input.txt
OUT=output.txt
Now we do something with those command line options...
$ ./bash--getopt_example --in input.txt --o=output.txt -d
DEBUG is enabled
IN=input.txt
OUT=output.txt
Now we do something with those command line options...
$
AddVariable () {
Variable1="$1"
Variable2="$2"
if [ "$#" -eq 0 ]
then
echo "provide an argument"
elif [ "$#" -ne 1 ] && [ "$#" -ne 2 ] || [ "$#" -eq 3 ]
then
echo "Surplus argument provided"
else
printname "$Variable1"
deletename "$Variable2"
fi
}
AddVariable $Variable1 $Variable2
Just for clarification are you trying to check arguments when running the script that is from the command line or calling the function? Arguments for your function are defined by your script as written and can't be changed real time. You still don't have an understanding for scope of variables.
#!/usr/bin/env bash
AddVariable () {
if [ "$#" -eq 0 ]
then
echo "provide an argument"
exit
fi
if [ "$#" -gt 1 ]
then
args=($@)
#print out excess arguments
echo "Surplus arguments provided"
for (( i=1; $i<=${#args[@]};i++))
do
echo ${args[$i]}
done
fi
}
deletename(){
if [[ -d "$1" ]]
then
#mess for first var deleted
echo "deleting from $1"
for file in $1/*; do
echo " rm -iv "$file""
done
else
echo "not a valid directory"
exit
fi
}
## send first arg to delete function
deletename $1
#send the rest up to be printed out if access is given
AddVariable $@
just my interpretation of what OP is trying to do, print out excess arguments, and delete the files in the first argument dir.
-- oops I read it again and ...
Quote:
Originally Posted by OP
My bash function is suppose to ask for an argument when it is not supplied and indicate surplus argument when the argument supplied is morethan three (3). But presently,when i supply it with 3 argument it does not echo "surplus argument" but give the same result with when i supply one or two argument. Please how do i correct this or is it from my bash logic combination?
below is the code:
Code:
if [[ $# -gt 3 ]]
then
tell someone what they are
fi
if you only give 3 then it is NOT greater than 3, yes?
AddVariable () {
Variable1="$1"
Variable2="$2"
if [ "$#" -eq 0 ]
then
echo "provide an argument"
elif [ "$#" -ne 1 ] && [ "$#" -ne 2 ] || [ "$#" -eq 3 ]
then
echo "Surplus argument provided"
else
printname "$Variable1"
deletename "$Variable2"
fi
}
AddVariable $Variable1 $Variable2
Just for clarification are you trying to check arguments when running the script that is from the command line or calling the function? Arguments for your function are defined by your script as written and can't be changed real time. You still don't have an understanding for scope of variables.
Is this homework?
yes i am trying to check arguments when running the script from the command line.
i am new to bash scripting and i am trying to understand how to use it,so i do try to solve some problems.When i run into difficulties i try to ask questions to be able to find my way around. Thank you
#!/usr/bin/env bash
AddVariable () {
if [ "$#" -eq 0 ]
then
echo "provide an argument"
exit
fi
if [ "$#" -gt 1 ]
then
args=($@)
#print out excess arguments
echo "Surplus arguments provided"
for (( i=1; $i<=${#args[@]};i++))
do
echo ${args[$i]}
done
fi
}
deletename(){
if [[ -d "$1" ]]
then
#mess for first var deleted
echo "deleting from $1"
for file in $1/*; do
echo " rm -iv "$file""
done
else
echo "not a valid directory"
exit
fi
}
## send first arg to delete function
deletename $1
#send the rest up to be printed out if access is given
AddVariable $@
just my interpretation of what OP is trying to do, print out excess arguments, and delete the files in the first argument dir.
-- oops I read it again and ...
Code:
if [[ $# -gt 3 ]]
then
tell someone what they are
fi
if you only give 3 then it is NOT greater than 3, yes?
so of course it now needs adjustments.
sorry,i had to adjust the question,because i noticed a mistake on it,instead of 3 arguments,its 2 arguments. thank you.
yes i am trying to check arguments when running the script from the command line.
Ok, to make things easier don't use a function for this check. You have been provided several different ways to verify the number of command line arguments. Try grail's and see if it works.
Ok, to make things easier don't use a function for this check. You have been provided several different ways to verify the number of command line arguments. Try grail's and see if it works.
i really i appreciate the time you guys take out to attend to my issues,but am yet to get the solution i desire,like i mention earlier,i want the if statement inside a function and also when i enter more than 3 arguments or zero argument,it should give me either surplus argument or provide an argument. Thank you.
You can use normal mathematical symbols if it helps the logic:
Code:
if (( $# > 0 && $# < 3 ))
then
printname "$Variable1"
deletename "$Variable2"
else
echo "Incorrect number of arguments supplied!"
echo "Usage :- ${0##*/} arg1 [arg2]"
fi
the above code works fine when the argument supplied is zero,one or two,but when the third argument is supplied,instead of giving the output as "Surplus argument" the result remains the same with when you supply one or two argument. Thank you
$# inside your function will never be greater then 2 regardless of the number command line arguments used to run your script. You need to change your logic a bit.
the above code works fine when the argument supplied is zero,one or two,but when the third argument is supplied,instead of giving the output as "Surplus argument" the result remains the same with when you supply one or two argument. Thank you
My point was to give you an alternative way to work the 'if'. Adding your requirement is a trivial addition using current information, which I leave to you
go back and re-look mine on post #5 to get more than required args given output. I think you might have gotten stuck on the one thing about 3 does is not greater than 3 part.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.