Determining length of string

I have this script which is very easy:

file=`echo 01114`
echo $file
01114

then I ran this

if [ $file -ge 7 ]; then echo "yes";fi

it returned yes even though there are only 5 digits there

So then I tried

file=`echo abcd`
echo $file
abcd
if [[ $file -ge 1 ]]; then echo "yes";fi
if [[ $file -gt 1 ]]; then echo "yes";fi

It did not return anything. How can I check with bash the length of a string of characters? I must be missing something

Try:

[ "${#file}" -gt 7 ] && echo yes

Note the hash char between the bracket and variable name.

hth

1 Like

By way of explanation, your code is trying to compare the numeric value of the variable, not the length. The code from sea uses an in-built function to generate the length as a value to compare against, although I would prefer it without the double-quotes. It might work depending on your OS. Some may be picky and complain that you are comparing a string with a numerical operator (the -gt )

I hope that this helps,
Robin