0

i need help with shell bash. I'm running it on ubuntu virtual machine My task is this # A three-digit number is given. Calculate the value of the second digit in the number. # For example, = 456 → = 5.

Here is what i have so far

read -r -p "enter the number" num

while (( $num > 0 )) ; do
        digit = "$((num % 10))"
        num ="$(( num / 10 ))"
        printf "num=%d digit=%d\n" "${num}" "${digit}"
done

Please tell me how i should expand my code so that it actually works , By the way the task is to calculate the digit with loops So doing it this way is no good even though its easier

read -r -p "enter the number: " num
printf "%s\n" "${num:1:1}"
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
clubmix
  • 31
  • 5
  • Please take a look at [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting). – Cyrus Jan 21 '23 at 18:08
  • `while (( num >= 10 ))` – pjh Jan 21 '23 at 18:20
  • what if the input is 0, 1, 2, or 4+ digits? what if something other than a number is entered? or do you need to first verify that a 3-digit *number* has been entered? – markp-fuso Jan 21 '23 at 18:51
  • 1
    @markp-fuso I am a beginner, so my task is just for three digit numbers, it doesn't need to account for negatives , non numbers or anything else – clubmix Jan 21 '23 at 19:19
  • see [substring extraction](https://tldp.org/LDP/abs/html/string-manipulation.html) , explains this syntax ```${string:position:length}``` as ```Extracts $length characters of substring from $string at $position.``` maybe ```echo ${num:1:1}``` will output ```5``` – atl Jan 21 '23 at 21:30
  • 1
    Please update the question to include details on what happens when you run your current script; I'm guessing you get some syntax and/or 'command not found' errors in which case the first thing you should consider doing is cutting-n-pasting your code (along with appropriate shebang) into [shellcheck.net](https://www.shellcheck.net/) ... this is a pretty good tool for flagging syntax issues. Once you've made the recommended changes to your code, and assuming you're still having problems, update the question with your latest code attempt and the (wrong) output generated by your code – markp-fuso Jan 21 '23 at 22:17
  • 1
    `digit = something` isn't assigning to a variable named `digit`, it's running a _command_ called digit (and giving you an error that that command doesn't exist -- an error you _should have_ included in this question). To have an assignment, you **must not** have spaces around the `=`. Once you fix that, `digit=$((num % 10))` works as-expected. – Charles Duffy Jan 21 '23 at 22:20

0 Answers0