Bash script. Creating a simple menu using the read command in Linux
ID: 351
Category: Bash Scripts
Added: 5th of June 2023
Views: 1,026
The bash script allows the user to create, add, clear and delete a .txt file using a simple menu in the terminal.
The bash script gets user input using the read -n1 command which is assigned to the opt variable. The -n1 switch limits the input to 1 character.
The bash script uses other elements including a function, if elif and else statement.
Copy and paste the code below to a new text file. Save the file as menu.sh then make the script executable by entering the following in the terminal
chmod +x menu.sh
To run the script enter the following command in the terminal
./menu.sh
#!/usr/bin/bash
menu()
{
echo ""
echo "1. Create .txt file"
echo "2. Add some text"
echo "3. View the .txt file"
echo "4. Clear the .txt file"
echo "5. Delete .txt file"
echo "6. Exit"
read -n1 opt
# Create .txt file
if [[ $opt = 1 ]]
then
touch /home/$USER/Desktop/NewFile.txt
clear
echo "Text File Created"
menu
# Add .txt to file
elif [[ $opt = 2 ]]
then
echo "this is a line" >> /home/$USER/Desktop/NewFile.txt
clear
echo "Text Added to File"
menu
# Display .txt file
elif [[ $opt = 3 && -f "/home/$USER/Desktop/NewFile.txt" ]]
then
clear
cat /home/$USER/Desktop/NewFile.txt
menu
# Clear .txt file
elif [[ $opt = 4 ]]
then
echo "" > /home/$USER/Desktop/NewFile.txt
clear
echo "Text File Cleared"
menu
# Delete .txt file
elif [[ $opt = 5 ]]
then
rm /home/$USER/Desktop/NewFile.txt
clear
echo "Text File Deleted"
menu
# Exit terminal
elif [[ $opt = 6 ]]
then
echo "Goodbye!!"
clear
exit
else
clear
menu
fi
}
menu