Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there is a parameter provided in bash?

I wanted to see if there is a parameter provided. But i don't know why this code wont work. What am i doing wrong?

   if ![ -z "$1" ]
   then
        echo "$1"
   fi
like image 760
tash517 Avatar asked Dec 15 '22 00:12

tash517


2 Answers

Let's ask shellcheck:

In file line 1:
if ![ -z "$1" ]
    ^-- SC1035: You need a space here.

In other words:

if ! [ -z "$1" ]
then
     echo "$1"
fi

If, as per your comment, it still doesn't work and you happen to be doing this from a function, the function's parameters will mask the script's parameters, and we have to pass them explicitly:

In file line 8:
call_it
^-- SC2119: Use call_it "$@" if function's $1 should mean script's $1.
like image 126
that other guy Avatar answered Dec 26 '22 10:12

that other guy


You could check the number of given parameters. $# represents the number of parameters - or the length of the array containing the parameters - passed to a script or a function. If it is zero then no parameters have been passed. Here is a good read about positional parameters in general.

$ cat script
#!/usr/bin/env bash

if (( $# == 0 )); then
    echo "No parameters provided"
else
    echo "Number of parameters is $#"
fi

Result:

$ ./script
No parameters provided
$ ./script first
Number of parameters is 1
$ ./script first second
Number of parameters is 2

If you would like to check the parameters passed to the script with a function then you would have to provide the script parameters to the function:

$ cat script
#!/usr/bin/env bash

_checkParameters()
{
    if (( $1 == 0 )); then
        echo "No parameters provided"
    else
        echo "Number of parameters is $1"
    fi
}

_checkParameters $#

This will return the same results as in the first example.

Also related: What are the special dollar sign shell variables?

like image 37
Saucier Avatar answered Dec 26 '22 10:12

Saucier