0

I'm pretty new with Bash scripting and am having trouble getting my 'while' loop to run. When I echo keywords, a whole list of words prints and then when I echo length, it prints 124. I believe I'm using the while loop and condition correctly, so I can't figure out what I'm doing wrong. Any thoughts?

keywords=$1
length=${#keywords}

echo "$keywords"
echo "$length"

if [ -z "$keywords" ]; then
    while [ $length -gt 100 ]; do
        echo "$keywords"
        echo "$length"

        keywords="${keywords%,*}"
        length=${#keywords}
    done
fi

echo $keywords

1 Answer 1

2

The problem is here:

[ -z "$keywords" ]

-z is true if its argument is an empty string. Something of length 124 is definitely far from empty. You probably meant -n.

Next time, please also include the input in the question so we can reproduce the problem.

Sign up to request clarification or add additional context in comments.

2 Comments

The entire if statement is unnecessary; if the string is empty, [ $length -gt 100 ] will fail and the loop will just be skipped.
I must have misread the documentation and had the empty string flag backwards. Thank you!

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.