Archive

Archive for the ‘Bash’ Category

How To Determine Directory of Sourced Bash Script

September 2nd, 2009 Masao No comments

Sourcing a script can be useful for exporting variables in the current shell.

However, you can’t use “dirname $0″ to get the directory of the script.

Here’s how to get the same effect of dirname, but still allowing you to export variables.

Relative path:

DIRNAME=${BASH_ARGV[0]%/*}

Full path:

ABSDIR=$PWD/${BASH_ARGV[0]%/*}

Categories: Bash, Linux Tags:

How to Fix an Empty Bash Shell Prompt

August 21st, 2009 Masao No comments

If you bash shell prompt is empty when logging in, here’s how to fix it.

Create a ~/.bashrc file:

if [ -f /etc/bashrc ]; then
	. /etc/bashrc
fi

Create a ~/.bash_profile file:

if [ -f ~/.bashrc ]; then
	. ~/.bashrc
fi
Categories: Bash, Linux Tags:

How to Convert Seconds to Minutes in BASH

July 22nd, 2009 Masao No comments

This is how to convert seconds into HH:MM:SS in bash:
$ date -d '1970-01-01 100 sec' +'%H:%M:%S'
00:01:40

Categories: Bash Tags:

How to Monitor Multi-Core CPU Usage on Linux

April 9th, 2009 Masao No comments

Here’s how to monitor multiple cores on Linux:

# mpstat -P ALL

Example:

Monitor all CPU’s in 1 second intervals forever

# mpstat -P ALL 1

Categories: Bash, Linux, Monitoring Tags:

How To Get Yesterday’s Date using BASH Shell Scripting

February 17th, 2009 Masao 2 comments

The new short way:
$ date -d '1 day ago' +'%Y/%m/%d'
2009/07/21

Or the longer way:
Yesterday in epoch seconds
$ yesterday=$((`date +'%s'` - 86400))

Get default formatted yesterday's date
$ date -d "1970-01-01 $yesterday sec"
Tue Feb 17 01:27:32 PST 2009

Same thing in YY-MM-DD
$ date -d "1970-01-01 $yesterday sec" +"%Y-%m-%d"
2009-02-17

Categories: Bash, Linux Tags:

How to View a Specific Page or Section of Manpage

November 30th, 2008 Masao No comments

For example, the “kill” manpage shows:

SEE ALSO
bash(1), tcsh(1), kill(2), sigvec(2), signal(7)

This is how to view section 7 of the “signal” manpage:

man 7 signal

Categories: Bash, Linux Tags:

Faster File Copy Using Tar and SSH

October 2nd, 2008 Masao 1 comment

How to quickly copy a file or directory over SSH using tar:

tar -cf – myfile | ssh target_host tar -xf -

If you want to change the target directory, use this:

tar -cf – myfile | ssh target_host “cd /target_dir; tar -xf -”

Categories: Bash, Linux Tags:

Copying directory trees with tar pipe tar

September 5th, 2008 Masao No comments

# tar cf – source_dir | ( cd target_dir && tar xBf – )

Categories: Bash, Linux Tags:

How to get the directory location of a shell script

March 26th, 2008 Masao No comments

dirname=`dirname $0`

Categories: Bash Tags: