Search for a string in files and save the result

Search all files in this directory and all subdirectories containing a specific string and save the result in a file + 25 characters before and after the file This helps me very often when I have to search huge amounts of data and the terminal window can’t handle the result.

grep -r -o -P '.{0,25}searchstring.{0,25}' ./ > ~/search_result.txt

-r = recursive
-o = only matching, just the fitting line
-P = use Perl regular expressions
./ = in the actual directory

The > saves all output into a specifc file, in this case, its inside your homedirectory ~

Check If Service Is Running

Simple bash snippet to check if a service is running, if not -> send a mail to root. In this snippet


if ps ax | grep -v grep | grep $SERVICE > /dev/null
echo "$SERVICE service running, everything is fine"
echo "$SERVICE is not running, try to start it."
sudo service $SERVICE start
echo "$SERVICE is not running!" | mail -s "$SERVICE down" root