0

I have a bash script that asks the user for 3 numbers (example, 123).

I'm stuck on how to separate these numbers in order to create file1, file2, file3, I also have to determine if they are unique.

Any help would be appreciated.

I can post my bash script if needed.

! /bin/bash
clear
echo -n "Enter three digits number: "
read number

echo $number | grep "^[0-9][0-9][0-9]$"
if [ "$?" -eq 1 ] 
then
   echo "Error!! Please enter only 3 numbers."
   exit 1
fi

if [ -d ~/a2/numbers ]
then
   rm -r ~/a2/numbers
fi
mkdir ~/a2/numbers

if [ ! -e ~/a2/products ]
then
   echo "Error the file \'products\'! does not exist"
   exit 1
fi
echo ' '
cat ~/a2/products

echo ' '
cut -f2 -d',' ~/a2/products > ~/a2/names
cat ~/a2/names

echo "I have $(cat ~/a2/names | wc -l) products in my product file"
echo ' '
3
  • 1
    Always post any code that you have. Try to post the most relevant parts if it is long. Commented Aug 9, 2012 at 4:08
  • 2
    I realized after I posted that I should have :(. My bad. Commented Aug 9, 2012 at 4:10
  • @crashez on a side note, bash can do regex without grep: if [[ $number =~ ^[0-9]{3}$ ]]; then ... Commented Aug 9, 2012 at 5:20

2 Answers 2

2

You could use the command fold which will split your string by character. Example:

echo ${number} | fold -w1

To check if they are unique just use the if statement, because in your case you allow only three one digit numbers.

Sign up to request clarification or add additional context in comments.

Comments

0
#!/bin/bash
read -p "enter 3 numbers: " nums
if [[ $nums != [0-9][0-9][0-9] ]]; then
  echo "digits only please"
  exit
fi

read n1 n2 n3 < <(sed 's/./& /g' <<< $nums)

if ((n1 == n2)) || ((n1 == n3)) || ((n2 == n3)); then
  echo "no duplicate numbers"
  exit
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.