how to check if $1 and $2 are null?

tay*_*oon 61 command-line bash scripts

I am running some script which passing the string argument and I want to do if else statement shown as below:

if [ $1 != '' ] && [ $2 != '' ]
then 
    do something.....
Run Code Online (Sandbox Code Playgroud)

but it shown Error too many argument. Why?

Syl*_*eau 81

Try using the -z test:

if [ -z "$1" ] && [ -z "$2" ]
Run Code Online (Sandbox Code Playgroud)

From man bash:

-z string
   True if the length of string is zero.
Run Code Online (Sandbox Code Playgroud)


mur*_*uru 18

由于这是标记为bash,我建议使用扩展测试结构 ( [[...]]),并忘记引号:

if [[ -z $1 && -z $2 ]]; then
...
Run Code Online (Sandbox Code Playgroud)

除非您要与sh/POSIX 兼容,否则没有理由不使用[[ ]].


Avi*_*Raj 5

The following also works,

if [ "$1" == "" && "$2" == ""]; then
    echo NULL
fi
Run Code Online (Sandbox Code Playgroud)