I am new to unix shell scripting. I am trying to execute sample function with arguments but the shell does not recognize the first argument as first but rather as second.
#!/bin/bash
func(){
echo "func"
if [ -z $1 ]
then echo "$1 received"
else echo "not received"
fi
}
func "hello"
gives output func not received
where it should have given
func
hello received
There are a few ways to do this. My preference is:
In this example, the second call will write "no argument passed". If you want to change the behavior, remove the colon after the
1
in the function definition. You can certainly usetest -n "$1"
(test
is the same as[
, except that you do not need a terminating]
argument) but it would be more appropriate to check the value of$#
, which gives a count of the number of arguments passed to the function.