'bash script while loop with read input from user [duplicate]
Wondering if there is an easy way to do what im attempting and the best way to go about something like this.
answer=y
while [ "$answer" = y ]
do
echo "type name of the file you wish to delete"
IFS= read -r file
echo "would you like to delete another file [y/n]?"
IFS= read -r answer
done
echo "Exiting Program"
exit 0
My questions here is when an input is entered it gets stored in file but I would like when the answer is y that it can then get stored to another variable like file1. Im then left with variables containing all the filenames someone wishes to delete which I can echo back.
How can I use a loop in this to keep adding the input until someone types n
Thanks for the help.
Solution 1:[1]
I wouldn't use a realtime read loop to delete files. Too many things can go wrong. Rather, maybe take a file of input and check each.
But for a simplistic answer to your question -
typeset -l answer=y # force to lowercase
lst=/tmp/file.list.$$
while [[ y == "$answer" ]]
do
echo "type name of the file you wish to delete"
IFS= read -r file
if [[ -e "$file" ]]
then echo "$file" >> $lst
else echo "That file does not exist/is not accessible."
fi
echo "would you like to delete another file [y/n]?"
IFS= read -r answer
done
echo -e "Files to be deleted:\n===\n$(<$lst)"
echo -e "\n===\n Delete all listed files [y/n]?"
IFS= read -r answer
if [[ y == "$answer" ]]
then rm $(<$lst)
fi
rm $lst
Solution 2:[2]
Maybe this helps:
while :; do
read -s -n 1 answer
if [ $answer = "y" || $answer = "Y" ]; then <your code>
elif [ $answer = "n" || $answer = "N" ]; then echo; echo; break
elif [ $answer = "" ]; then continue # pressed: return key
fi
done
depending the shell you use, you might use: [[ ${answer} =~ (Y|y) ]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |