Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Wednesday, March 27, 2013

Emacs in Daemon mode

When I started to use emacs as Java IDE, I have installed CEDET and JDEE. This make start time of emacs longer, even when I am not opening any Java file. Therefore, it is required to start Emacs in daemon mode. So that only one time startup is longer, and subsequent startup of emacs (emacs client to be precise) will be much faster.

I have written the following shell script (em, please place it in your $PATH), which starts the emacs daemon on first time only, and connects emacsclient to it.
#!/bin/bash

usr=$(whoami)
emacs_daemon="emacs --daemon"
cmd="ps auxww | grep \"$usr.*$emacs_daemon\" | grep -v grep"
#echo "$cmd"
is_running=$(eval "$cmd")
if [ -z "$is_running" ]
then
    echo "Starting emacs daemon"
    eval "$emacs_daemon"
    if [ $? -ne 0 ]
    then
        echo "$0: Cannot start $emacs_daemon" >&2
        exit
    fi
fi
emacsclient -a "" -t "$@"
exit $?

First Run:
$ em Hello.java
Starting emacs daemon

Warning: due to a long standing Gtk+ bug
http://bugzilla.gnome.org/show_bug.cgi?id=85715
Emacs might crash when run in daemon mode and the X11 connection is unexpectedly lost.
Using an Emacs configured with --with-x-toolkit=lucid does not have this problem.
("emacs")
Loading /usr/share/emacs/site-lisp/site-start.d/auto-complete-init.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/auto-complete-init.el (source)...done
Loading /usr/share/emacs/site-lisp/site-start.d/emacs-color-theme-init.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/emacs-color-theme-init.el (source)...done
Loading /usr/share/emacs/site-lisp/site-start.d/emacs-goodies-loaddefs.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/emacs-goodies-loaddefs.el (source)...done
Loading /usr/share/emacs/site-lisp/site-start.d/focus-init.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/focus-init.el (source)...done
Loading /usr/share/emacs/site-lisp/site-start.d/gnuplot-init.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/gnuplot-init.el (source)...done
Loading /usr/share/emacs/site-lisp/site-start.d/gnus-bonus-init.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/gnus-bonus-init.el (source)...done
Loading /usr/share/emacs/site-lisp/site-start.d/php-mode-init.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/php-mode-init.el (source)...done
Loading /usr/share/emacs/site-lisp/site-start.d/rpm-spec-mode-init.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/rpm-spec-mode-init.el (source)...done
Loading /usr/share/emacs/site-lisp/site-start.d/rpmdev-init.el (source)...
Loading /usr/share/emacs/site-lisp/site-start.d/rpmdev-init.el (source)...done
Loading /usr/share/emacs/site-lisp/cedet-1.1/common/cedet.el (source)...
Setting up CEDET packages...
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Setting up CEDET packages...done
Loading /usr/share/emacs/site-lisp/cedet-1.1/common/cedet.el (source)...done
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1                                                                                                  
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1                                                                                                  
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
jde-java-font-lock: building names cache...
jde-java-font-lock: building names cache...empty
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Warning: cedet-called-interactively-p called with 0 arguments, but requires 1
Starting Emacs daemon.

Second and Subsequent Runs:
$ em Hello.java

Tuesday, May 24, 2011

CPU Frequency Scaling

I have written a small shell script to increase or decrease CPU frequency. By default, it shows current CPU Frequency Scaling Governor. This can be changed only by root user. So this script needs to be run as root user or sudo as root, while changing the CPU Frequency Scaling governor.


#!/bin/bash

available_governors=$(cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_available_governors \
| head -1 | sed -e 's/ \([a-zA-Z0-9]\)/|\1/g' -e 's/ $//')
if [ $# -ne 1 ]
then

echo "USAGE: $0 [$available_governors]"
fi

echo "Command line to change CPU Scaling."
echo " - By Mitesh Singh Jat"
echo ""

## CPU Governor path
#/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
function current_cpu_governor ()
{
echo -n "Current CPU Scaling Governor is: "
cpu_scaling_governor="NOT SET"
for governor in $(ls /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor)
do
cpu_scaling_governor=$(cat $governor)
done
echo "$cpu_scaling_governor"
}

current_cpu_governor;

## Exit, if no governor is provided
new_governor=""
if [ $# -eq 0 ]
then
exit 0
else
new_governor="$1"
fi

## Run as root always
user_id=`whoami`
if [[ "$user_id" != "root" ]]
then
echo "$0: please run this script as root user."
exit
fi

if [ -z $(echo $available_governors | sed -e 's/^/|/' -e 's/$/|/' | grep "|$new_governor|") ]
then
echo "Sorry, this mode '$new_governor' is not supported."
exit 1
else
echo "Setting CPU into '$new_governor' Mode..."
fi
## Now set cpu governor to the given mode
for governor in $(ls /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor)
do
echo "$new_governor" > $governor
done
current_cpu_governor;

exit 0



Sample Run

Getting current CPU Frequency Scaling Governor
$ cd /path/where/cpu_scaling.sh/is/copied/
$ ./cpu_scaling.sh
USAGE: ./cpu_scaling.sh [powersave|conservative|ondemand|userspace|performance]
Command line to change CPU Scaling.
- By Mitesh Singh Jat

Current CPU Scaling Governor is: ondemand


Increasing CPU frequency (Please run as root).
$ ./cpu_scaling.sh performance
Command line to change CPU Scaling.
- By Mitesh Singh Jat

Current CPU Scaling Governor is: ondemand
./cpu_scaling.sh: please run this script as root user.
$ sudo ./cpu_scaling.sh performance
[sudo] password for mitesh:
Command line to change CPU Scaling.
- By Mitesh Singh Jat

Current CPU Scaling Governor is: ondemand
Setting CPU into Performance Mode...
Current CPU Scaling Governor is: performance
$ ./cpu_scaling.sh
USAGE: ./cpu_scaling.sh [powersave|conservative|ondemand|userspace|performance]
Command line to change CPU Scaling.
- By Mitesh Singh Jat

Current CPU Scaling Governor is: performance


Decreasing CPU frequency
$ sudo ./cpu_scaling.sh ondemand
Command line to change CPU Scaling.
- By Mitesh Singh Jat

Current CPU Scaling Governor is: performance
Setting CPU into OnDemand Mode...
Current CPU Scaling Governor is: ondemand

Monday, October 26, 2009

Better Console Calculator Using bc

If we use expr for mathematical calculations on console (terminal), it is frustrating, and hard to remember syntax and escape sequences used in expr. :( This small tip will help us.

Just add following line in your .bashrc file (~/.bashrc).

function calc
{
echo "${1}" | bc -l;
}

Then update the shell environment by:

$ source ~/.bashrc


"calc" from the shell will work as follows:

$ calc 2+3
5
$ calc 1+2*3
7
$ calc 1.1*2
2.2
$ calc "(1+2)*3"
9
$ calc "(1+2)^3"
27
$ calc "s(.5)"
.47942553860420300027

Monday, October 5, 2009

Converting Improper mp3 into Proper mp3 for Nokia E71

The music player of Nokia E71 is vulnerable to improper mp3. It stucks forever, even if there is a single improper mp3. Improper mp3 is a mp3 file which does not conform to mp3 standard, there are some problem in mp3 headers. For more information on improper mp3, please read manual of checkmp3 command.

$ man checkmp3

I have written a shell script which converts improper mp3's into proper mp3.



#!/bin/bash

## Script to fix mp3 files using checkmp3

## Checking existance of checkmp3
checkmp3=`which checkmp3`

if [[ "$checkmp3" == "" ]]
then
echo "$0: please install checkmp3."
exit
fi

if [ $# -ne 1 ]
then
echo "USAGE: $0 <mp3_file|dir_with_mp3s>"
exit
fi

dir="$1"
file=""

if [[ -d "$dir" ]]
then
echo "processing directory '$dir'"
temp_file="$dir/fixed.mp3"
for file in `find "$dir" -iname "*.mp3" | sed 's/ /\\\_/g'`
do
file=`echo "$file" | sed 's/\\\_/ /g'`
echo "processing file '$file'"
$checkmp3 -i -sf "$file" > "$temp_file"
if [ $? -ne 0 ]
then
echo "$0: error in processing file '$file'"
else
#eyeD3 "$temp_file"
#$checkmp3 "$temp_file"
mv "$temp_file" "$file"
fi
done
rm -f "$temp_file"
else
file="$dir"
echo "processing file '$dir'"
dir=`dirname "$file"`
temp_file="$dir/fixed.mp3"
echo "$temp_file"

$checkmp3 -i -sf "$file" > "$temp_file"
if [ $? -ne 0 ]
then
echo "$0: error in processing file '$file'"
else
#eyeD3 "$temp_file"
#$checkmp3 "$temp_file"
mv "$temp_file" "$file"
fi
fi
exit 0



Sample run:

$ ./fix_mp3.sh xyz.mp3
$ ./fix_mp3.sh /path/to/mp3/directory/

Thursday, September 10, 2009

Disabling Macbook Pro Touchpad

We may want to disable Macbook Pro (or any other Laptop) Touchpad, such cases are:
(i) We have connected a USB mouse, so we do not want to use touchpad for now.
(ii) While typing, there is no use of touchpad, if touchpad is too sensitive, the cursor keeps on jumping due to slight touch of palm or finger.

I have written a script to disable/enable touchpad (which is using synaptics driver).





#!/bin/bash

## Disable touchpad if USB Mouse is attached

SYNAPTICS=`which synclient`

if [[ "$SYNAPTICS" == "" ]]
then
echo "$0: please install synaptics touchpad driver."
echo "Also make sure that 'Option \"SHMConfig\" \"on\"'"
echo " is added in Touchpad device Section in /etc/X11/xorg.conf"
exit
fi

USB_mouse_present=`grep -ic "usb.*mouse" /proc/bus/input/devices`
# if no USB Mouse; enable touchpad
if [ $USB_mouse_present -eq 0 ]
then
$SYNAPTICS TouchpadOff=0
else
$SYNAPTICS TouchpadOff=1
fi

# if any parameter [on|off] is given, override previous command
if [ $# -ge 1 ]
then
if [ "$1" = "on" ]
then
$SYNAPTICS TouchpadOff=0
else
$SYNAPTICS TouchpadOff=1
fi
fi

exit 0



Sample Run:
Turn on touchpad

$ ./touchpad.sh on

Turn off touchpad

$ ./touchpad.sh off

If we have plugged USB mouse, then just give following command

$ ./touchpad.sh

On removing USB mouse, give following, the touchpad will be enabled automatically. :)

$ ./touchpad.sh


PS: The configuration for synaptics driver can be referred from here or here.

Friday, September 4, 2009

IP Masquerade and Network Address Translation (NAT)

If we want to connect multiple computers to the Internet using single public IP Address, Masquerading (A form of NATing) helps us.

NAT describes the process of modifying the network addresses contained with datagram headers while they are in transit. IP masquerade is the name given to one type of network address translation that allows all of the hosts on a private network to use the Internet at the price of a single IP address.

IP masquerading allows you to use a private (reserved) IP network address on your LAN and have your Linux-based router perform some clever, real-time translation of IP addresses and ports. When it receives a datagram from a computer on the LAN, it takes note of the type of datagram it is, “TCP,” “UDP,” “ICMP,” etc., and modifies the datagram so that it looks like it was generated by the router machine itself (and remembers that it has done so). It then transmits the datagram onto the Internet with its single connected IP address. When the destination host receives this datagram, it believes the datagram has come from the routing host and sends any reply datagrams back to that address. When the Linux masquerade router receives a datagram from its Internet connection, it looks in its table of established masqueraded connections to see if this datagram actually belongs to a computer on the LAN, and if it does, it reverses the modification it did on the forward path and transmits the datagram to the LAN computer.

I have written a shell script, which converts a Linux box into a router. The script is written as:




#!/bin/bash

## Output interface: connected to Internet
out_iface=ppp0

## Run as root always
user_id=`whoami`

if [[ "$user_id" != "root" ]]
then
echo "$0: please run this script as root user."
exit
fi

## Checking existance of iptables
IPTABLES=`which iptables`

if [[ "$IPTABLES" == "" ]]
then
echo "$0: please install iptables."
exit
fi

if [ $# -ge 1 ]
then
case "$1" in
status)
$IPTABLES -t nat -L
exit 0
;;
stop)
## Disabling Packet forwarding in kernel
echo 0 > /proc/sys/net/ipv4/ip_forward
echo "Flushing NAT MASQUERADE Entries"
$IPTABLES -t nat -F
exit 0
;;
restart)
$0 stop
if [ $# -ge 2 ]
then
$0 start $2
else
$0 start
fi
;;
start)
if [ $# -ge 2 ]
then
out_iface=$2
fi
## Enabling Packet forwarding in kernel
echo 1 > /proc/sys/net/ipv4/ip_forward

## Enabling NAT Masquerade, if not enabled
if [ -z "`$IPTABLES -t nat -L | grep MASQUERADE`" ]
then

$IPTABLES -t nat -A POSTROUTING -o $out_iface -j MASQUERADE
fi
;;
*)
echo "USAGE: $0 <start|status|restart|stop> [internet_interface]"
exit 1
;;
esac
else
echo "USAGE: $0 <start|status|restart|stop> [internet_interface]"
exit 1
fi

exit 0



Sample Runs:

$ ./NAT_Masquerade.sh
./NAT_Masquerade.sh: please run this script as root user.
$ sudo ./NAT_Masquerade.sh
USAGE: ./NAT_Masquerade.sh [internet_interface]
$
Here, internet_interface is the interface which is connected to internet.
By default, ppp0 (Dial up) interface is taken.

$ sudo ./NAT_Masquerade.sh status
Chain PREROUTING (policy ACCEPT)
target prot opt source destination

Chain POSTROUTING (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination
$
Since Masquerade is not yet applied, Chain POSTROUTING rule is empty.

Applying IP Masquerade to internet_interface eth0.
$ sudo ./NAT_Masquerade.sh start eth0
$ sudo ./NAT_Masquerade.sh status
Chain PREROUTING (policy ACCEPT)
target prot opt source destination

Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
MASQUERADE all -- anywhere anywhere

Chain OUTPUT (policy ACCEPT)
target prot opt source destination
$ sudo ./NAT_Masquerade.sh stop
Flushing NAT MASQUERADE Entries
$

Tuesday, June 2, 2009

Web Access through Proxy Server by Terminal Applications

In many companies/Universities, the web access is granted through Proxy Server (Usually SQUID; hence port 3128).
There are many terminal applications (run on command line interface), which access Internet/Web. For example:
wget (to download file), ftp, lynx/links (to access website), apt/yum (to download and install package). If we are behind
proxy, these applications do not work. The easy solution is to set some shell environment variables, explained below:

For accessing web(lynx/links) using a non-authenticated proxy:
$ export http_proxy="http://proxy.yourcompany.com:3128"

Verify that the setting took place
$ echo $http_proxy
http://proxy.yourcompany.com:3128

For accessing web(lynx/links) using a authenticated proxy:
$ export http_proxy="http://username:password@proxy.yourcompany.com:3128"

If you want the change to be permanent (there each time you open a terminal),
add the export line to .bashrc in your 'home' directory.
$ echo 'export http_proxy="http://proxy.yourcompany.com:3128"'″ >> ~/.bashrc

Secure HTTP (over SSL) access
$ export https_proxy="https://proxy.yourcompany.com:3128"

FTP access
$ export ftp_proxy="ftp://proxy.yourcompany.com:3128"

Tuesday, January 13, 2009

Playing Directory in Mplayer

In order to play media files inside a directory with mplayer, I have written a shell script. Please save it in a directory in your $PATH variable.

For example, ~/bin/mplayer_dir.sh

#!/bin/bash


# Plays files inside a directory with mplayer

playlist="/home/mitesh/.mplayer/playlist.txt"

dir="./"
if [[ $# > 0 ]]
then
dir=$1
fi

#rm -f $playlist
find "$dir" -iname "*" | egrep -i "\.(wma|wmv|flv|mp3|avi|vob|dat|mp4|m4v|ogg|divx|xvid|rmvb|rm|asf)$" | sort > $playlist
#cat $playlist
nlines=`wc -l $playlist | awk '{print $1}'`

if [[ $nlines > 0 ]]
then
mplayer -playlist $playlist
else
echo "$0: Unrecognized files in $dir"
echo "Please update this script if playable format is present."

fi

--------------

Sample Run:

$ mplayer_dir.sh [directory]

Tuesday, November 4, 2008

Counts from min to max

In order to get counts from start number to end number,
I have written a shell script.


#!/bin/sh

if [ $# -ne 2 ]
then
echo "Usage: $0 min max"
exit
fi


min=$1
max=$2

while [ $min -le $max ]
do
echo -n $min " "
min=`expr $min + 1`
done
#end script



Sample run:
$ ~/bin/count.sh 2 5
2 3 4 5

Tip: This is very handy script, that is very helpful
in getting counts in the loop. For example:
$ for i in `~/bin/count.sh 2 8`
> do
> echo "Hello $i"
> done

Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8

Wednesday, October 1, 2008

Viewing PDF Files on Terminal

First you need to convert a PDF document to HTML, then you run it through the elinks pager. There's a fine utility for doing just that, and it's called (appropriately) pdftohtml. You can find the home page for pdftohtml. If pdftohtml isn't already installed in your distribution of Linux, or isn't on your CD set, it's commonly available for Debian and RPM-based distributions, such as Fedora, SUSE, and more. The elinks program is also easily available if it isn't automatically installed in your distribution.
For example, you can install pdftohtml and elinks in Debian Linux with this command:
# apt-get install pdftohtml elinks

Users of the yum package can get the RPM version with this command:
# yum -y install pdftohtml elinks

Now you can view a PDF document with the following command. This particular command has one drawback. The output will not include frames (PDF files generally have a frame on the left that lets you jump to different pages).

$ pdftohtml -q -noframes -stdout document .pdf | elinks

If you want the left frame of page numbers, you can always use the following command instead:

$ pdftohtml -q document .pdf ; elinks document .html

You can write a script to save you all this typing each time you view a document. Use sudo or log in as root to create the /usr/local/bin/viewpdf script and enter the following code:

#!/bin/bash

pdftohtml -q $1 ~/temp.html
elinks ~/temp.html

#
#end of script

This code assumes it's OK to store the temporary HTML file in your home directory. You can use another location if you prefer. Now save your work and make the file executable:

$ sudo chmod +x /usr/local/bin/viewpdf

Tuesday, June 10, 2008

Process Status of Any Process Containing given String

In order to get Process Status (ps) of any process containing given string
(say 'mitesh'), we use to type following commands, which are long and
tedious to type.

$ ps auxww | grep "mitesh" | grep -v grep

Instead, if we type

$ psg.sh mitesh

which is more convenient to type. So what this '
psg.sh'
contains (I am assuming, that
~/bin is in $PATH):

$ vi ~/bin/psg.sh

#!/bin/bash
function is ()
{
ps auxww | grep "$@" | grep -v "grep"
}

is $@

# END : psg.sh

Monday, June 9, 2008

Shortcuts for Working in BASH (Bourne Again SHell)

Navigation
Left/right cursor key --- Move left/right in text
Ctrl+A --- Move to beginning of lIne
Ctrl+E --- Move to end of line
Ctrl+right arrow --- Move forward one word
Ctrl+left arrow --- Move left one word

Editing
Ctrl+U --- Delete everything behind cursor to start of line
Ctrl+K --- Delete from cursor to end of line
Ctrl+W --- Delete from cursor to beginning of word
Alt+D --- Delete from cursor to end of word
Ctrl+T --- Transpose characters on left and right of cursor
Alt+T --- Transpose words on left and right of cursor

Miscellaneous
Ctrl+L --- Clear screen (everything above current line)
Ctrl+U --- Undo everything since last command
Alt+R --- Undo changes made to the line
Ctrl+Y --- Undo deletion of word or line caused by using Ctrl+K, Ctrl+W, and so on
Alt+L --- Lowercase current word (from the cursor to end of word)


Note: If you find these shortcuts hard to remember and you know vi(m),
you can enable vi mode for editing command line using following command:

$ set -o vi

To enable vi mode from start of Bash, add following lines to your ~/.bashrc
# Start vi Mode for command line editing
set -o vi



Wednesday, April 16, 2008

Group By Counts in a File (Generally csv files)

You can use following snippet to get GROUP BY - COUNT as in SQL
query. Like

If you want number of students in a department:

SELECT department, COUNT(*) FROM Student GROUP BY department;

Suppose that this file contains:

Mitesh Singh Jat,CSA
Mahesh Singh Sonal,CSA
Paneendra B A,SSA
Shrikant Joshi,SERC
Rupesh Bajaj,CSA
Chandrakant,SSA

1 #!/bin/bash
2
3 if [[ $# <> 4 ]]
4 then
5 echo "Usage: $0 file delim field_pos
6 exit
7 fi
8
9 CMD=`echo $1 | sed 's/.*\.gz/zcat/'`
10
11 if [[ $CMD != "zcat" ]]
12 then
13 CMD="cat"
14 fi
15
16 echo "========================"
17 echo "Buckets for $1"
18 echo "========================"
19 echo "Bucket_id Count"
20 echo "------------------------"
21 $CMD $1 | cut -d$2 -f$3 | awk '{sum[$1]++} END {for (x in sum) {out+=sum[x]; print x" \t"sum[x];} print "========================"; print "Total records : " out;}'
22 echo "========================"

$ ./group_by_count.sh Student , 2
========================
Buckets for Student
========================
Bucket_id Count
------------------------
SSA 2
SERC 1
CSA 3
========================
Total records: 6
========================


Monday, March 31, 2008

Dynamic Swap on File

1. Create a 500MB swap file.

$ dd if=/dev/zero of=/mnt/WinD/Swap500M bs=1024 count=500000
$ mkswap /mnt/WinD/Swap500M



2. Change variables according to your configuration (or liking) in
the following Shell script (my_swapon.sh).

#!/bin/sh

## Turns on swap ##

SWAP_PARTITION="/mnt/WinD"
SWAP_DEV="$SWAP_PARTITION/Swap500M"
if [[ -e $SWAP_DEV ]]
then
echo "$SWAP_DEV is already mounted."
else
mount $SWAP_PARTITION
fi

IS_ON=`grep -c $SWAP_DEV /proc/swaps`

if [ $IS_ON -eq 1 ]
then
echo "$SWAP_DEV is already turned on."
else
swapon $SWAP_DEV
fi


3. Run this script as root user whenever you want to
use extra swap space. (Above steps 1 and 2, need
to be done only once).

$ sudo ./my_swapon.sh