0

I am a newbie .Please help me with this

The output says syntax error near unexpected token 'do'

The code is

if [ $# -eq 0 ];
then 
echo "Command line arguments are missing."
else
n=$1
sum=0
while[ $n -gt 0 ]
do
   rem=$(( $n % 10 ))
   sum=$(( $sum + $rem ))
   n=$(( $n / 10 ))
done 
echo "Sum of digit for given number is $sum "
fi
Ravi Kd
  • 39
  • 8
  • If you are a newbie, stop using `[`. At the very least, just replace it with the equivalent, but far more readable `test`. `if test $# -eq 0; ..` and `while test $n -gt 0; ...`. It becomes immediately clear why `whiletest $n...` is an error. – William Pursell Jul 14 '17 at 14:54

2 Answers2

0

A whitespace after while. Try this out:

if [ $# -eq 0 ];
then
  echo Command line arguments are missing.
else
  n=$1
  sum=0
  while [ $n -gt 0 ];
  do
     rem=$(( $n % 10 ))
     sum=$(( $sum + $rem ))
     n=$(( $n / 10 ))
  done
  echo "Sum of digit for given number is  $sum"
fi
lazyneuron
  • 537
  • 5
  • 12
0

Put spaces before and after [ and ].
You can replace the while-loop with

sum=$(( $(echo $1| sed 's/./&+/g; s/+$//' ) ))
Walter A
  • 19,067
  • 2
  • 23
  • 43