0

I have just started to learn shell scripting. I could not find an answer for this problem online.

The function given below takes an argument and checks if the length of string passed is non zero or not.

function length_checker {
    echo "number of arguments passed = $#"
    if [ $# -ne 1 ]
    then
        echo "Please pass an argument"
    elif [ -z $1 ]
    then
        echo "length of passed argument is zero"
    else
        echo "length of passed argument is non zero"
    fi
}

RANDOM_VAR='hello'
RANDOM_VAR2=''
length_checker $RANDOM_VAR2

Output:

number of arguments passed = 0
Please pass an argument

Problem:

since RANDOM_VAR2 is an empty string, and it is being passed in length_checker method, I was expecting the output to be "length of passed argument is zero".

However, it gives "number of arguments passed = 0".

I wanted to know how why is the argument not getting passed, and how to do so, such that it prints "length of passed argument is zero"?

  • 1
    Quote your variables. `length_checker $RANDOM_VAR2` is equivalent to `length_checker`. You wanted `length_checker ""` so you have to write `length_checker "$RANDOM_VAR2"`. – Socowi Mar 13 '22 at 09:20
  • 1
    Please add a suitable shebang (`#!/bin/bash`) and then paste your script at http://www.shellcheck.net/ and try to implement the recommendations made there. – Cyrus Mar 13 '22 at 10:02

0 Answers0