In this tutorial, we will create a small Bash script to take a user input string and place it into a grep which then pipes the output to a file.
First we need to create a new .sh file and add this at the very top:
Code: Select all
#!/bin/bash
Next we will add a while true do loop. Essentially this tells Bash to continuously loop through the program while true (this program is always true):
Code: Select all
while true; do
The 'read' line tells Bash that we want to wait and read user input. This is helpful for menu systems, like this one.
Code: Select all
echo "Please choose an option:"
echo " 1. Pipe user defined dmesg output to a text file."
echo " 2. Pipe all dmesg output to a text file."
echo " 3. Exit the Program."
read -p "-> " menuResponse
The '-n' in the echo means that the user input will stay on the same line as the echo text. Instead of being on a newline. It is required to also end using a ';' for each new statement while inside the case system.
The '1)' means that (if the user hits the 1 key) then.
Code: Select all
case $menuResponse in
1) echo -n 'Input Keywords: ';
The code that will use this value is a regular grep command to take a value from dmesg. We will use this value to automate the command, so we don't have to type it in the terminal each time.
It is important to properly structure the user input variable (userKeyword) by 'double quoting' and using Bash's variable symbol '$' and the place paranthesis around the actual name we used for the variable. The '>' tells grep that we want to pipe the output to a text file.
Again we end the statement using a semi-colon and a break command which will 'break' us out of the continuous loop. We end this with a double ';;' so it ends the program.
Code: Select all
read userKeyword;
dmesg | grep -i "${userKeyword}" > dmesg_user_defined.txt;
break;;
'csac' ends the case menu (it is case spelled backwards). Done is easy, it means we are done so please exit cleanly.
Code: Select all
*) echo 'Invalid Option.';;
esac
done
A complete example that I wrote is below (which has added functionality):
Code: Select all
#!/bin/bash
#Author: ATSB
#Licence: GPL2
while true; do
echo "-------------------------"
echo "---- DMESG COMMANDER ----"
echo "---------1.0-------------"
echo "Please choose an option:"
echo " 1. Pipe user defined dmesg output to a text file."
echo " 2. Pipe all dmesg output to a text file."
echo " 3. Exit the Program."
read -p "-> " menuResponse
case $menuResponse in
1) echo -n 'Input Keywords: ';
read userKeyword;
dmesg | grep -i "${userKeyword}" > dmesg_user_defined.txt;
break;;
2) dmesg > dmesg_all.txt;
break;;
3) echo 'Exiting..';
break;;
*) echo 'Invalid Option.';;
esac
done