0

I have a shell script print function like below:

print_status()
{
 echo "$1|$2|$3|$4"
 paramArr=("$@")
 for i in "${#paramArr[@]}"
 do
   if [[ -z ${paramArr[i]} ]];
   then
       paramArr[i]="Unknown"
   fi
 done
 echo "${paramArr[*]}"
}

The function is supposed to print 4 values, with "|" as a delimiter. I have kept the print statement at the top of the function, just to show how the actual values to be printed.

I also wanted to check that each argument coming to this function, if is a blank value (i.e the variable actually contains nothing), then print "Unknown". I wanted to get this done via an array paramArr as above. But It doesn't work as expected.

Example :

Output1:
Running|162.103.172.46|3.345|-0.076
Running 162.103.172.46 3.345 -0.076 Unknown

Expected Output 1:
Running|162.103.172.46|3.345|-0.076
Running 162.103.172.46 3.345 -0.076 <-- With a "|" instead of space


Output2:
Not Running|||
Not Running    Unknown

Expected Output2:
Not Running|||
Not Running Unknown Unknown Unknown <-- With a "|" instead of space

What exactly is going wrong/missing in my function ?

1
  • for i in "${#paramArr[@]}" is a wrong construct, to loop over array elements Commented Feb 27, 2018 at 8:09

1 Answer 1

1

You have several issues. First you are counting array indexes from zero to the number of elements. When that is 4 then you go from 0 - 4, which is 5 elements, so you get an extra one. When it is fewer than 4 then it won't add the 'Unknown' because you are not iterating far enough.

Second, when you print an array using [*] inside quotes, the delimiter between elements is the first character of $IFS, which by default is a space:

print_status()
{
    echo "$1|$2|$3|$4"
    paramArr=("$@")

    for ((i=0; i < 4; i++))
    do
        if [[ -z ${paramArr[i]} ]];
        then
            paramArr[i]="Unknown"
        fi
    done

    oldIFS="$IFS"
    IFS='|'
    echo "${paramArr[*]}"
    IFS="$oldIFS"
}

print_status Running 162.103.172.46 3.345 -0.076
print_status 'Not Running'

Gives:

Running|162.103.172.46|3.345|-0.076
Running|162.103.172.46|3.345|-0.076
Not Running|||
Not Running|Unknown|Unknown|Unknown
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.