LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This 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


Reply
  Search this Thread
Old 12-18-2019, 01:05 PM   #1
dan-german
LQ Newbie
 
Registered: Dec 2019
Posts: 6

Rep: Reputation: Disabled
Unhappy 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:

#!/bin/bash

Variable1="$1"
Variable2="$2"

AddVariable () {

Variable1="$1"
Variable2="$2"

if [ "$#" -eq 0 ]
then
echo "provide an argument"

elif [ "$#" -ne 1 ] && [ "$#" -ne 2 ]
then
echo "Surplus argument provided"
else

printname "$Variable1"
deletename "$Variable2"

fi

}

deletename(){

for file in $Variable/*;do

echo "$(rm -i "$file")"
echo "deleting $Variable"

done
}
printname(){
Variable=$1
for file in $Variable/*;do

echo "$(basename "$file")"
done
}

#printname "$Variable1"
#deletename "$Variable2"
AddVariable $Variable1 $Variable2

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
 
Old 12-18-2019, 01:54 PM   #2
jmgibson1981
Senior Member
 
Registered: Jun 2015
Location: Tucson, AZ USA
Distribution: Debian
Posts: 1,141

Rep: Reputation: 392Reputation: 392Reputation: 392Reputation: 392
Code:
if [[ "$3" ]] && [[ ! "$4" ]] ; then
	echo "${1} ${2} ${3}"
else
	echo "to many / not enough args"
fi
this will only echo at 3 arguments.

You don't need to define a variable to hold "$1" or any other positional. Just call it directly.

Code:
printname "$1"
also, use code tags to wrap your scripts when you post, makes easier to read.

for what it's worth, i have no clue what the goal of this script is. doesn't make much sense to me. what are you trying to achieve.

Last edited by jmgibson1981; 12-18-2019 at 02:00 PM.
 
Old 12-18-2019, 03:16 PM   #3
rnturn
Senior Member
 
Registered: Jan 2003
Location: Illinois (SW Chicago 'burbs)
Distribution: openSUSE, Raspbian, Slackware. Previous: MacOS, Red Hat, Coherent, Consensys SVR4.2, Tru64, Solaris
Posts: 2,803

Rep: Reputation: 550Reputation: 550Reputation: 550Reputation: 550Reputation: 550Reputation: 550
Quote:
Originally Posted by dan-german View Post
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...
$
HTH...
 
1 members found this post helpful.
Old 12-18-2019, 04:35 PM   #4
michaelk
Moderator
 
Registered: Aug 2002
Posts: 25,702

Rep: Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896
Code:
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?
 
Old 12-18-2019, 05:47 PM   #5
BW-userx
LQ Guru
 
Registered: Sep 2013
Location: Somewhere in my head.
Distribution: Slackware (15 current), Slack15, Ubuntu studio, MX Linux, FreeBSD 13.1, WIn10
Posts: 10,342

Rep: Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242
Code:
#!/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 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:
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.

Last edited by BW-userx; 12-18-2019 at 05:59 PM.
 
Old 12-18-2019, 11:41 PM   #6
dan-german
LQ Newbie
 
Registered: Dec 2019
Posts: 6

Original Poster
Rep: Reputation: Disabled
Talking

Quote:
Originally Posted by michaelk View Post
Code:
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
 
Old 12-19-2019, 12:32 AM   #7
dan-german
LQ Newbie
 
Registered: Dec 2019
Posts: 6

Original Poster
Rep: Reputation: Disabled
Talking

Quote:
Originally Posted by BW-userx View Post
Code:
#!/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.
 
Old 12-19-2019, 01:59 AM   #8
grail
LQ Guru
 
Registered: Sep 2009
Location: Perth
Distribution: Manjaro
Posts: 10,007

Rep: Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192
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
 
Old 12-19-2019, 03:28 AM   #9
michaelk
Moderator
 
Registered: Aug 2002
Posts: 25,702

Rep: Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896
Quote:
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.

Last edited by michaelk; 12-19-2019 at 03:30 AM.
 
Old 12-19-2019, 04:15 AM   #10
dan-german
LQ Newbie
 
Registered: Dec 2019
Posts: 6

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by michaelk View Post
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.
 
Old 12-19-2019, 04:20 AM   #11
dan-german
LQ Newbie
 
Registered: Dec 2019
Posts: 6

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by grail View Post
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
 
Old 12-19-2019, 05:12 AM   #12
michaelk
Moderator
 
Registered: Aug 2002
Posts: 25,702

Rep: Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896Reputation: 5896
AddVariable $Variable1 $Variable2

$# 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.

https://linuxize.com/post/bash-funct...ariables-scope

Last edited by michaelk; 12-19-2019 at 05:29 AM.
 
Old 12-19-2019, 11:53 AM   #13
grail
LQ Guru
 
Registered: Sep 2009
Location: Perth
Distribution: Manjaro
Posts: 10,007

Rep: Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192
Quote:
Originally Posted by dan-german
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
 
Old 12-19-2019, 04:17 PM   #14
BW-userx
LQ Guru
 
Registered: Sep 2013
Location: Somewhere in my head.
Distribution: Slackware (15 current), Slack15, Ubuntu studio, MX Linux, FreeBSD 13.1, WIn10
Posts: 10,342

Rep: Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242Reputation: 2242
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.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Logic vs "Logic" bluegospel General 153 09-03-2013 05:20 PM
LSI Logic / Symbios Logic 53c875 (rev 14) -> HP Storageworks 1/8 G2 gileravxr Linux - Hardware 0 07-21-2009 04:45 AM
Bind Mouse Button Combination to Keyboard Key Combination? neoAKiRAz Linux - Desktop 0 05-04-2007 12:49 PM

LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 07:13 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration