Useful bashrc functions
I’m going to share some of my bashrc functions that save me a lot of time.
Killer
This function helps you find and kill a process by keyword. Instead of running ps aux, piping to grep, and manually killing by PID, just give it a keyword and it will take care of the rest.
killer() {
echo "I'm going to kill these process";
ps -ef | grep $1 | grep -v grep
echo "Can I ? [y]es [n]o ";
read ans;
if [[ $ans =~ "y" ]] ;
then
ps -ef | grep $1 | grep -v grep | awk '{print $2}' | xargs kill -s TERM
fi
}
Usage: killer chromium
You will be given a list of processes matching the keyword and prompted to proceed with yes or no. Update: This function is not that useful anymore; you can use the built-in pkill command to get the same result.
Search and cd combined
This function will help you search and cd into a folder in a single step.
scd() {
pathe=$(find ~ -name "${1}" -type d -print -quit | head -n 1)
cd "${pathe}"
}
You might wonder why we save the result to a variable before cd-ing into it.
The exec flag in find expects an executable binary (like /bin/bash), and cd is a shell builtin, which means you would have to leave the parent shell to cd into a folder. A one-liner for the same looks like this:
find ~ -name $1 -type d -exec bash -c "cd '{}'; exec bash" \;
Note that you will be taken into a new shell, and any changes you make there will not be reflected in the parent shell. Exiting each shell manually is a pain.
You can have a look at my stackoverflow post regarding the doubts I had with this implementation.
If you have any suggestions for improvement, please leave a comment.
Usage: scd Music
Will take you to the Music folder, regardless of your current working directory.
Mkdir and cd into it in a single step
Creating a directory and cd-ing into it is something I had to do very often.
mkcd() {
mkdir "${1}"
cd "${1}"
}
A dictionary
Due to my poor vocabulary, I always had to look up words on dictionary.com. So I wrote a bash script to fetch meanings from within my terminal.
dict() {
#Creating a temp folder
dir=~/.dict
#Check for the existence if not create one
[[ -d $dir ]] || mkdir $dir
#download respective file from dictionary dot com
# -q => do it quietly ie nothing @ screen
# -O save it as mean
wget -q -O $dir/mean wget http://dictionary.reference.com/browse/$1
#Please DONT hardcode the value, give it to variable and then use it
file=$dir/mean
#greping out result
m=$(cat $file | grep description | grep -Po 'content=.*.*See more' | grep -Po '\,.*.\.')
#saving the error code
k=$(echo $?)
#echoing
echo "Meaning of the word "$1" is"$m
#checks if the word was actually available else throws an error
if [[ $k -gt 0 ]];
then
echo ".........oops, cant find word "$1;
fi
}
I love doing hacks around bash, you can find more of these here.