0

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
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
  • 1
    Are trying to test that an argument is given, or that the argument is a non-empty string? If the latter, then using `test -n` is fine. If the former, you ought to be checking the value of `$#`. (What response do you want to `func ""`?) – William Pursell Jan 06 '15 at 13:40

2 Answers2

6

Your test should be:

if [ -n "$1" ]

instead of if [ -z $1 ]

  • -n: variable is not empty
  • -z: variable is empty

NOTE you best add the quotes around $1; else it will not work when you pass no argument.

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
  • 2
    Specifically, `[ -z $1 ]` when no arguments are passed becomes `[ -z ]` which is interpreted by `[`/`test` as `[ -n -z ]` which is always true. – Etan Reisner Jan 06 '15 at 14:08
3

There are a few ways to do this. My preference is:

#!/bin/bash
func(){ echo ${1:-no argument} passed; }
func "hello"
func ""
func

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 use test -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.

func() { 
    if test $# -lt 1; then
        echo no argument passed
    else
        echo at least one argument passed
    fi
}
William Pursell
  • 204,365
  • 48
  • 270
  • 300