Luca
Luca

Reputation: 453

Create files based on user input

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 ' '

Upvotes: 0

Views: 732

Answers (2)

glenn jackman
glenn jackman

Reputation: 246837

#!/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

Upvotes: 0

golja
golja

Reputation: 1093

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.

Upvotes: 2

Related Questions