Question about armstrong numbers

when i was having problems with trying to do arithmetic expansion and then adding it to a variable i decided to see how others had solved this problem.

i seen an unusual expression that i haven’t seen before in others answers. what i would like is more info on it, where i can look it up, what it’s called…

i’ll put mine here –

An=$1
total=0

for ((x=0; x<"${#An}"; x++)); do
    total=$(( "$total" + "${An:$x:1}" ** "${#1}" ))
done

it’s what is getting added to the total in braces, the An.... part

thank you

${An:$x:1} is a Shell Parameter Expansion. Particularly it is the ${parameter:offset:length} form that gets you a substring.

The offset is zero-based

$ x=hello
$ echo ${x:3:2}
lo

bash provides various parameter expansions that in other languages might be:

  • length
  • substring
  • trimleft & trimright
  • sub & gsub
  • “if x (is|is not) null then …”
    • set x to y
    • return y
  • toupper & tolower
  • and more

thank you for answering

when i look at ‘man bash’ AND your ‘hello’ explanation then what the man page was saying makes more sense. i have seen this in some of the basic python that i have played with.

cool, thank you

take care
em

I am trying Armstrong numbers for the first time, and am having a similar issue.

In a loop, when trying to get the total sum of all passes, it’s not summing the numbers, it’s just presenting them like a single string.

> char=0

>  26 while [[ $char -lt 3 ]]
>  27 
>  28  do
>  29 
>  30    result+=$(( ${num:char:1}**count_of_chars ))
>  31   
>  32    ((char++))
>  33  
   35  done
>  36 
>  37 echo $result

Using the number 153 as a test, the sum of $result should be 153:
1 + 125 + 27=153
Instead, it prints 112527, which is each iteration of the loop with no white space.

What am I doing wrong?

Thanks

Here are a couple of resources that might help:

Unless specifically declared as an integer, var+= assumes it’s a string and does string concatenation. Use (( and $(( for arithmetic.

That worked, thank you.