Wednesday, December 21, 2016

Modifying PS1 for bash.

You can change your bash prompt to be more informative:




This prompt is showing the user (root) at IP, the currently opened folder and the git branch if you are in a git repo.

To change your prompt add these lines to ~/.bashrc (for the first prompt shown above)

\[\e[0;31m\] Some Text Here \[\e[m\]

This will color "Some Text Here" red.

parse_git_branch determines the git branch (if you are in a git project directory) and appends it to PS1.

For displaying time you can use : \t or \T. See : ( for more options.

For changing the prompt to look like the second one above:

For the third prompt shown above:

For the fourth prompt shown above:

Monday, December 19, 2016

Searching file names recursively using regex

This perl program searches the current working directory recursively for file names matching the regex supplied by user and prints the results.

Advanced sorting (multiple keys) in perl.

Sometimes you need to sort data like this:
1. Sort by numeric value first.
2. If numeric values are equal, sort by name.

Here's the code for doing this in perl :
Let's suppose I have a hash of hashrefs. (eg. $distance{$city}= $some_number).
This hash stores distances of citites (keys) from a particular city. Now we want to sort by distance first (ascending) and if two citites are at equal distance, we want to sort on the basis of names :

To sort on descending order, we just replace $a with $b and vice versa:

How does this work?

The <=> operator is equivalent to :

so if $a == $b we get to the second test for OR operator which compares the strings similarly. If even the names of strings are equal, we return 0 which tells the sort function that these two entries are equal and order for them doesn't matter to us.

Getting PIDs of all instances of a particular script

This perl code finds the PIDs of all instances of a particluar file.

Let's say you have a file /home/user/script and lets say you have 4 multiple instances of it running on your computer at the same time. You want to find the PIDs of all of them. You can use this :

ps -ef | grep your_file_name | grep -v grep | awk '{print $2}'

You'll have all 4 PIDs separated by a new line character.

Setting system volume on startup (Ubuntu)

This script sets system volume to 0% on Mon-Fri if the system boots up between 8AM to 7PM (so your laptop doesn't shout when you receive some notification).

Otherwise, sets the volume to 100% (when you are at home :D).

#!/usr/bin/perl -w

my ($hour, $wday) = (localtime(time))[2, 6];

open my $log_h, ">>", "/tmp/volume_script_log";

my $vol = ($wday>0 && $wday<6)?(($hour >= 8 && $hour <=19)?0:100):100;

print $log_h "Day of the week is $wday, hour is $hour, setting volume to $vol%\n"; close($log_h);

`amixer -D pulse sset Master $vol%`

For running on start :

Add an entry to crontab file :

#1 (Open crontab file)

crontab -e

#2 (Add this line)

@reboot perl /path/to/