Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
echo enter a number
read n
count=0
while[$n=!0]
do
count=$((count+1))
n=$((n/10))
done
echo number of digits = $count
This is my code for counting the number of digit in a number but it doesn't coz the terminal says
enter a number
23
./countdigits.sh: line 6: while[23=!0]: command not found
./countdigits.sh: line 7: syntax error near unexpected token `do'
./countdigits.sh: line 7: `do'
I updated the software but the error is still there
Welcome. You'll want to install the utility called shellcheck and use it often. There is also a web site of the same name which will also test shell scripts.
In the future, please wrap your scripts in [code] [/code] tags so that indentation is preserved.
# Declare following two vars as integer
declare -i n
declare -i count
echo Enter a Number:
read n
# the way I compare to integers (not using the posix method you are trying)
# "-gt" for greater than
# "-gte" for greater than or equal
# "-ne" for not equal
# "-lt" for less then
# "-lte" for less than or equal
# Also - note the spacing around the brackets below... don't try to save any spaces, it won't work.
count=0
while [ $n -ne 0 ]
do
count=${count}+1
n=${n}/10
done
# Declare following two vars as integer
declare -i n
declare -i count
echo Enter a Number:
read n
# the way I compare to integers (not using the posix method you are trying)
# "-gt" for greater than
# "-gte" for greater than or equal
# "-ne" for not equal
# "-lt" for less then
# "-lte" for less than or equal
# Also - note the spacing around the brackets below... don't try to save any spaces, it won't work.
count=0
while [ $n -ne 0 ]
do
count=${count}+1
n=${n}/10
done
echo number of digits = $count
The $(( )) was correct; don't make it worse!
Agreed, [ $n -ne 0 ] compares as numbers, and is straighter than [ $n != 0 ] that compares as strings (alphabetically).
The spaces are required because [ is actually a command that wants a ] as last argument. (This is compatible with the old archaic Bourne shell. But also the modern [[ ]], not yet in the Posix standard, needs the spaces.)
--
$(( )) enforces a numeric context and yields a value.
While (( )) enforces a numeric context and does not yield a value, and is not yet in the Posix standard.
Code:
#!/bin/bash
echo enter a number
read n
count=0
while ((n!=0))
do
((count++))
((n/=10))
done
echo "number of digits = $count"
If you're going to use user supplied input in numeric context inside a (( )), [[ ]] or $(( )) then you need to validate it first as numeric context is unsafe and can lead to shenanigans!
Code:
$ read n && [[ n -gt 0 ]] && echo yes
(PATH=0)
$ echo $PATH
0
... Yikes!
Code:
$ read n && (( n > 0 )) && echo yes
(PATH=0)
$ echo $PATH
0
... Yikes!
The same is true for a declare -i n ; read n construct, except that there's no way to validate the input as it's already too late:
I decided to do a benchmark on the various ways I could come up with of validating the input using the output of seq 1 1000000.
Results
Surprisingly, I found that "case" was the fastest and most efficient:
Code:
$ cat /tmp/test-case
#!/bin/bash
while read n
do
case $n in
*[^0-9]* ) exit 1 ;;
esac
done < <( seq 1 1000000 )
$ time /tmp/test-case
real 0m12.819s
user 0m8.324s
sys 0m6.593s
$
Next, but not that far behind, was a [[ ]] extglob pattern using 0-9
Code:
$ cat /tmp/test-pattern_0-9
#!/bin/bash
while read n
do
[[ "$n" != +([0-9]) ]] && exit 1
done < <(seq 1 1000000 )
$ time /tmp/test-pattern_0-9
real 0m14.186s
user 0m9.615s
sys 0m6.474s
$
(note: I also tried using the == *[^0-9]* pattern similar to that used in the "case" here but the results were the same as for the extglob: suggesting that the performance loss over "case" is down to [[ ]] being used ).
Next up, and perhaps not unsurprisingly, an extglob using the [:digit:] abstraction:
Code:
$ cat /tmp/test-pattern_digit
#!/bin/bash
while read n
do
[[ "$n" != +([[:digit:]]) ]] && exit 1
done < <( seq 1 1000000 )
$ time /tmp/test-pattern_digit
real 0m15.806s
user 0m10.285s
sys 0m7.083s
... not much in that one.
Now the difference start to get significant...
Next up: a [ ] test using -ge 0 and -le 0
Code:
$ cat /tmp/test-gele
#!/bin/bash
while read n
do
! [ "$n" -ge 0 -o "$n" -le 0 ] 2>/dev/null && exit 1
done < <( seq 1 1000000 )
$ time /tmp/test-gele
real 0m26.326s
user 0m18.732s
sys 0m9.724s
$
Last, and trailing far behind the rest: regex
Code:
$ cat /tmp/test-regex
#!/bin/bash
while read n
do
[[ ! "$n" =~ ^[0-9]+$ ]] && exit 1
done < <( seq 1 1000000 )
$ time /tmp/test-regex
real 0m45.975s
user 0m35.188s
sys 0m11.226s
$
Yes, thankyou. I just realised that after posting and corrected my post. For some reason I'd gotten it into my head that [[ was builtin but [ wasn't. (probably because I remembered there's a [ in /usr/bin).
That one uses n in the unsafe numeric context we were trying to avoid by testing. edit: nevermind. Sorry, I misread what you had written (not going to post again until I've had another coffee!)
Second one is a good idea though. Using sub is slightly slower than the extglob solutions:
Code:
$ cat /tmp/test-sub
#!/bin/bash
while read n
do
[[ -n "${n//[0-9]}" ]] && exit 1
done < <(seq 1 1000000 )
$ time /tmp/test-sub
real 0m16.193s
user 0m12.101s
sys 0m6.483s
$
That one uses n in the unsafe numeric context we were trying to avoid by testing.
Second one is a good idea though. Using sub is slightly slower than the extglob solutions:
Code:
$ cat /tmp/test-sub
#!/bin/bash
while read n
do
[[ -n "${n//[0-9]}" ]] && exit 1
done < <(seq 1 1000000 )
$ time /tmp/test-sub
real 0m16.193s
user 0m12.101s
sys 0m6.483s
$
those should be used together, the second one alone does not work for empty strings, but you can skip the first step, if you know n is non-empty.
Otherwise you can do a numeric check too, something like this:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.