I need to get the amount of numbers entered from a parameter and assign them to variables [closed]

StackOverflow https://stackoverflow.com/questions/23177413

  •  06-07-2023
  •  | 
  •  

Question

I am making a program that will have the user provide a 3 digit number when running the program. If it does not have 3 numbers, then Im to give an error message. How can I test the length of the number and also how can I assign each number out of those digits to a variable?

Thanks for any help in advance!

I tried doing: grep '^[0-9][0-9][0-9]$' but that did not work.

Was it helpful?

Solution

Consider the following as a starting point. Add more error checking for getting practice.

#!/bin/bash

while : 
do
    read -p "Enter a three digit number or q to quit: " input
    if (( input >= 100 && input <= 999)); then 
        echo "good entry"
        digit1=${input:0:1} && echo "digit1 is $digit1"
        digit2=${input:1:1} && echo "digit2 is $digit2"
        digit3=${input:2:1} && echo "digit3 is $digit3"
    elif [[ $input == "q" ]]; then
        break
    else
        echo "bad entry"
    fi
done

Output:

Enter a three digit number or q to quit: 4256
bad entry
Enter a three digit number or q to quit: 242
good entry
digit1 is 2
digit2 is 4
digit3 is 2
Enter a three digit number or q to quit: 562
good entry
digit1 is 5
digit2 is 6
digit3 is 2
Enter a three digit number or q to quit: q
###program breaks here

OTHER TIPS

Do you really want a variable for each number in the user submission?

ie - foo_one = 1, foo_two = 2, foo_three = 3 ?

Or do you just want to iterate them and "do something" with each one?

Here's something I just threw together that might help you on the right track:

#!/bin/bash

die() { printf "%s\n" "$@" 1>&2; exit 1; }

read -p "Enter 3 digit number " num

if [[ "${#num}" -lt 3 ]]; then
        die "Error: Please enter at least 3 digits."
else
        for (( i=0; i<${#num}; i++ )); do
                echo " var $i is ${num:$i:1}"
        done
fi

OUTPUT:

$ ./sotest.sh
Enter 3 digit number 123
var 0 is 1
var 1 is 2
var 2 is 3

Sorry if this doesn't help. Maybe you can provide some more info on the overall goal?

#!/bin/bash

userInput=$1

if [ $(grep -o "[0-9]" <<< $userInput | wc -l) -ne 3 ] || \
    [ $(grep -o "[a-z]" <<< $userInput | wc -l) -gt 0 ] || \
    [ $(grep -o "[A-Z]" <<< $userInput | wc -l) -gt 0 ]; then 
   echo "Provide exactly a 3-digit number. No letters, just Numbers..."; 
   exit 1;
else
   digi1=$(grep -o "[0-9]" <<< $userInput | awk 'NR==1{print}');
   digi2=$(grep -o "[0-9]" <<< $userInput | awk 'NR==2{print}');
   digi3=$(grep -o "[0-9]" <<< $userInput | awk 'NR==3{print}');

   echo "Digit-1 is $digi1";
   echo "Digit-2 is $digi2";
   echo "Digit-3 is $digi3";
fi

Output :

]$  ./test.bash 134
   Digit-1 is 1
   Digit-2 is 3
   Digit-3 is 4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top