First of all, I’d like to thank everyone here for the help they’ve given me in the past. I love Arch, but so many in Arch-specific communities can be snobby toward people just trying to learn.
Anyway, here’s my issue: I have a (very outdated) programming background, and I’m working on learning bash. Right now I’m trying to figure out IF statements and variables. Here is some pseudo-code of what I want to do:
Do you want to execute command #1? Y/N If YES, set bool1 to true, else set bool1 to false and move on to next question
Do you want to execute command #2? Y/N If YES, set bool2 to true, else set bool2 to false and move on to next question, etc.
If bool1=true, touch file1.txt, else end IF statement If bool2=true, touch file2.txt, else end IF statement, etc.
I’ve looked at online tutorials, but I think I just need a nudge in the right direction. I feel like if I can get this simple task written, I’ll be able to modify it from there. Thanks for anyone’s help!
#!/usr/bin/env bash
# Read for user input, `-p` means display a prompt
read -p 'Are you sure? [Y/n] '
# By default `read` stores the response in a variable named `REPLY`
# One method of validating the input is a case statement.
# This will accept case-incensitive y/n or yes/no
case $REPLY in
[Yy]|[Yy][Ee][Ss])
echo 'Yes'
;;
[Nn]|[Nn][Oo])
echo 'No'
;;
*)
echo 'Unrecognized'
esac
How i’d solve what you want to do:
#!/usr/bin/env bash
read -p 'Do you want to execute command #1? Y/n '
# Convert the reply to lowercase and create the file if it's 'y'
[[ ${REPLY,,} == 'y' ]] && touch 'file1.txt'
# Same thing but in a different format
read -p 'Do you want to execute command #2? Y/n '
if [[ ${REPLY,,} == 'y' ]]; then
# Quotes not needed here but always quote '' if a path might have spaces.
# Use double quotes "" if you need to expand a variable.
touch 'file2.txt'
fi