Argument check- bash - bash

Suppose I have a script that takes two arguments, is there way to check if there is one argument or 2+ arguments in say the form:
if [ check if arguments don't equal 2 ]; then
echo Too many arguments
exit 1
fi

if [ $# -ne 2 ]; then
# Number of arguments was not 2
fi
The variable $# holds the number of passed arguments.

Related

Validate the number of arguments passed in bash from read

I have a question about validating user input regarding number of arguments passed by the user in a bash script.
For example, if I use:
if [[ $# -eq 2 ]]
then...
that will check if 2 arguments passed from the command line like this:
./somescript.sh arg1 arg2
but how to validate if user passed 2 arguments when asked?
For example:
echo "Type 2 names:"
read...
if [[ user passed more || less than 2 arguments]]
echo "incorrect number of names"
Now if I try to use $# -eq 2 it doesn't work.
What's the proper way to do it?
Use an array:
read -r -a array
if [[ "${#array[#]}" -eq 2 ]]; then ...
See output of:
declare -p array
Alternatively if your shell has no array like ksh or POSIX shell, you can populate the arguments from the read variable like this:
read -r reply
set -f # Disable globbing
set -- $reply # without quotes
if [ $# -eq 2 ]; then

Determining if there is a next argument while iterating through the arguments

While iterating through the arguments, how do you determine if there is a next argument?
The way I tried to approach this was to check if the next argument is not empty but I ran into some problems.
Here in this example I print the value of the current argument and if there is an argument that comes after that then print some message.
My approach:
use $i+1 where $i+1 will give you the value of the next index.
#!/bin/sh
for i in "$#"
do
echo $i
if ! [ ${i+1}="" ]; then
echo "test"
fi
done
sh test 1 2 3 4 5
but that didn't work. I also tried expr i + 1, but that didn't work as well.
If anyone could give me a hint on how to approach this problem that would be really appreciated.
#!/bin/sh
while [ $# -gt 0 ] ; do
echo $1
if [ -n "${2+x}" ]; then
echo another arg follows
fi
shift
done
$ ./test.sh 1 2 3
1
another arg follows
2
another arg follows
3
The trick here is that we use shift for consuming the argument list instead of iterating over it. The next argument is always $1, which we know exists because we only execute the loop if $# (the count of the positional arguments, not including $0) is positive. To check whether the argument after that, $2, exist, we can use the ${PARAM+WORD} expansion, which produces nothing if PARAM doesn't exist, otherwise produces WORD.
Of course, shift destroys the argument list. If you don't want that, move things into a function. The following example shows how we can process the same argument list twice by passing a copy into a function in which shift locally eats it:
#!/bin/sh
func() {
while [ $# -gt 0 ] ; do
echo $1
if [ -n "${2+x}" ]; then
echo another arg follows
fi
shift
done
}
func "$#"
func "$#"
$ ./test.sh 1 2 3
1
another arg follows
2
another arg follows
3
1
another arg follows
2
another arg follows
3
You can use a counter and check for $#:
n=1
for i in "$#"; do
echo "$i"
if [ $n -eq $# ]; then
echo "test"
fi
n=$(expr $n + 1)
done

How to check for the existence of a second argument [duplicate]

This question already has answers here:
How do I find the number of arguments passed to a Bash script?
(4 answers)
Check existence of input argument in a Bash shell script
(12 answers)
Closed 7 years ago.
I need to update this bash function I use for doing things with git:
push() {
a=$1
if [ $# -eq 0 ]
then
a=$(timestamp)
fi
# ... do stuff
}
but I don't know how this line works
if [ $# -eq 0 ]
I need to check for a first argument and then I need to check for a second argument.
So there will be 2 if statements.
How can I update this and how does this line work
if [ $# -eq 0 ]
The $# part is a variable that contains the number of arguments passed to the script.
The conditional statement there checks the value of that variable using -eq and it's checking if the value is zero (as in no arguments were passed).
In order to check for two arguments, you can change (or add) that line to read like this:
if [ $# -eq 2 ]
You could create a small script to look into how $# changes when you call the function with different numbers of arguments. For instance:
[Contents of "push.sh":]
push() {
echo $#
}
echo "First call, no arguments:"
push
echo "Second call, one argument:"
push "First argument"
echo "Third call, two arguments:"
push "First argument" "And another one"
If you put this in a script and run it, you'll see something like:
-> % ./push.sh
First call, no arguments:
0
Second call, one argument:
1
Third call, two arguments:
2
This tells you that the value of $# contains the number of arguments given to the function.
The if [ $# -eq 0 ] part you can add to the script, and change the 0 to some other numbers to see what happens. Also, an internet search for "bash if" will reveal the meaning of the -eq part, and show that you could also use -lt or -gt, for instance, testing whether a number is less than or greater than another.
In the end, you'll likely want to use something like the following:
a=$1
b=$2
if [ $# -lt 1 ]
then
a=$(timestamp)
fi
if [ $# -lt 2 ]
then
b=$(second thing)
fi

I have a script and I want it to tell me how many paramters it has

I need it to tell me how many parameters i have in the program but it's not working the way I want
if [ "$#" -ne 1 ];
then
echo "Illegal number of parameters is"
me=`basename $0`
echo "File Name: $0"
echo "First Parameter : $1"
fi
When you echo the $# variable, it gives you the number of parameters passed to the script
Content of script.sh
#!/bin/bash
echo "Number of parameters passed are $#"
$ chmod u+x script.sh
$ ./script.sh apple 1 2 ball 3
Number of parameters passed are 4
$# contain all you want whether passed argument to script or number of positional parameters passed to the function.
#!/bin/bash
myfunc(){
echo "The number of positional parameter : $#"
echo "All parameters or arguments passed to the function: '$#'"
echo
}
printf "No of parameters passed:$#\n"
myfunc test123
myfunc 1 2 3 4 5
myfunc "this" "is" "a" "test"
Like
$ ./sample.sh 1 2 3 4 5
No of parametere passed:5
The number of positional parameter : 1
All parameters or arguments passed to the function: 'test123'
The number of positional parameter : 5
All parameters or arguments passed to the function: '1 2 3 4 5'
The number of positional parameter : 4
All parameters or arguments passed to the function: 'this is a test'

How do I find the number of arguments passed to a Bash script?

How do I find the number of arguments passed to a Bash script?
This is what I have currently:
#!/bin/bash
i=0
for var in "$#"
do
i=i+1
done
Are there other (better) ways of doing this?
The number of arguments is $#
Search for it on this page to learn more:
http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST
#!/bin/bash
echo "The number of arguments is: $#"
a=${#}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$#"
do
echo "The length of argument '$var' is: ${#var}"
(( count++ ))
(( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"
to add the original reference:
You can get the number of arguments from the special parameter $#. Value of 0 means "no arguments". $# is read-only.
When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.
see Bash Reference Manual in section 3.4.2 Special Parameters:
"The shell treats several parameters specially. These parameters may only be referenced"
and in this section for keyword $# "Expands to the number of positional parameters in decimal."
Below is the easy one -
cat countvariable.sh
echo "$#" | awk '{print NF}'
Output :
#./countvariable.sh 1 2 3 4 5 6
6
#./countvariable.sh 1 2 3 4 5 6 apple orange
8

Resources