I am writing a script using a function that is it supposed to install a package by giving to the function the name of the package.
I am asking to the user if he wants to install that packet and, to do so, I wrote a regex, but the thing is: my regex is ignored, I can write anything in the output it will works. Howewer, I want the user to write something specific in order to install the package.
#!/bin/bash
OK=$'\033[92m' #GREEN
BASIC=$'\033[96m' #BLUE
RESET=$'\033[0m' #RESET COLOR
CHECK_MARK=$'\033[0;32m\xE2\x9C\x94\033[0m' #CHECKMARK
function install_package() {
answer=""
while [[ ! ($answer =~ ^y$|Y$|Yes$|YES$|yes$|n$|N$|no$|No$|NO$|q$|Q$|Quit$|quit$) ]]
do
echo -en "${BASIC}Do you want to install $1 ? (y|n|q)${RESET}"
answer=$(read)
if [[ $answer =~ ^y$|Y$|Yes$|YES$|yes$ ]]
echo "test"
then
echo -ne "${OK}Installation of $1 ${RESET}"
apt-get install "$1" -y &>/dev/null
echo -e "\\r${CHECK_MARK}${OK} $1 has been installed or is already installed. ${RESET}"
break
fi
done
}
install_package "micro"
echo "test"
And my output:
root@test-deb:/home/user/bashthings# ./p.sh
Do you want to install micro ? (y|n|q)y
test
✔ micro has been installed or is already installed.
test
root@test-deb:/home/user/bashthings# ./p.sh
Do you want to install micro ? (y|n|q)fege8geg655eg
test
✔ micro has been installed or is already installed.
test
root@test-deb:/home/user/bashthings#
It might be confusing but what I am asking is why my regex is not filtering any of what I type ?
apt-getto/dev/null. Write it to a log file instead, e.g.apt-get install "$1" -y 2>&1 >> /var/log/my_script.logand also output a message that tells the user that the log file is available. It will make problem resolution easier for the user.set -eto the start of the script. It will terminate the script if an error occurs. (Or handle errors.apt-getcan sometimes fail in very strange ways and for weird reasons. Misconfigureddpkgis frequent source of weird failures.) Instead ofset -e, you can also add-eto the shebang line:#! /bin/bash -eecho "test"is between theifand its associatedthen; I'd have to think about that for a bit but I'm guessing this is treated similarly toif [[ $answer =~ ... ]] || echo "test"; then ..., and sinceecho "$test"is treated as 'true' thethenblock is always executed; move theecho "$test"somewhere else (eg, before theif; between thethenandfi; after thefi) and see if your script now behaves as desired