Skip to content

Instantly share code, notes, and snippets.

@tisaconundrum2
Created January 20, 2019 21:51
Show Gist options
  • Save tisaconundrum2/eca8dda9348dbada58690042b856b7f5 to your computer and use it in GitHub Desktop.
Save tisaconundrum2/eca8dda9348dbada58690042b856b7f5 to your computer and use it in GitHub Desktop.
#!/bin/bash
# [ ] 1. the name or number. If it exists in the directory, then the line should be displayed.
# [ ] 2. both. The entry is displayed if it exists and is added if it doesn’t exist in the file.
# [x] 1. Assign the pathname to the file teledir.txt to a variable, say, TELEDIR.
# [x] For example, if it is in your home directory, you’ll need to assign $HOME/teledir.txt to the variable TELEDIR
# [x] 2. Check that one or two arguments are supplied using $# and the case…esac construct.
# [x] 1. If one or two arguments are supplied, do nothing
# [x] 2. otherwise, Indicate that the usage must be in the form scriptname [name number], then exit
# [x] 3. Using the $# and the case…esac construct,
# [x] 1. If one argument is supplied,
# [x] 1. If it starts with a digit, search it in the file.
# [x] 1. If it doesn’t exist, echo that “Number doesn’t exist”
# [x] 2. If it starts with a letter (lower or uppercase), search it in the file.
# [x] 1. If it doesn’t exist, echo that “Name doesn’t exist”
# [x] 2. If two arguments are supplied, set the search_pattern to be “name: number”, and search it in the file.
# [x] 1. If it is not found, echo “Adding entry”, and append to the file/variable.
# [x] 2. Otherwise, echo that “Entry exists”
TELEDIR="./teledir.txt"
bad_input () {
echo "Incorrect arguments"
echo "Usage: ./teledir.sh \"John\" 123-456-7890"
echo "Usage: ./teledir.sh 123-456-7890"
echo "Usage: ./teledir.sh \"John\""
exit
}
validate () {
valid=$(grep -Ec "(${1})" $TELEDIR)
if [[ $valid -gt '0' ]]; then
grep -E "(${1})" $TELEDIR
else
echo "$2 doesn't exist"
fi
}
one_argument () {
num_valid=$(echo "$1" | grep -Ec "([0-9]{3}-){2}[0-9]{4}$")
nam_valid=$(echo "$1" | grep -Ec "[a-zA-Z]+")
if [[ num_valid -eq 1 ]]; then
validate "$1" "Number"
elif [[ nam_valid -eq 1 ]]; then
validate "$1" "Name"
else
bad_input
fi
}
two_argument () {
valid=$(grep -Ec "(${1}): (${2})" $TELEDIR)
if [[ $valid -eq 1 ]]; then
echo "Entry exists"
else
echo "Adding Entry"
echo "$1: $2" >> $TELEDIR
fi
}
case $# in
1) one_argument "$1" ;;
2) two_argument "$1" "$2";;
*) bad_input ;;
esac
@mmunoz8486
Copy link

How do you set up your code so that it reads the user's input?
Plugging in your code the way you have it now, even if I add a "read" command, only spews out what you have echoed under "bad_input"
It does not go through the rest of the script.

@tisaconundrum2
Copy link
Author

Honestly, I legit forgot about this code. What did throwing it through GPT do? 😂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment