Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Friday, August 15, 2008

Check if Process is Running [Unix]

If you have a process id (pid), how can you tell if it is still running?

One obvious way to do this is to parse the output of the ps command. For example:

sharfah@starship:~> ps -ef | grep " 1234 " | grep -v grep
sharfah  1234     1  0 10:36:06 pts/65   1:20 java -server
However, a much neater way to do this is to use the kill command to send signal 0 to the process. So kill -0 will not terminate the process and the return status can be used to determine if the process is running. 0 if it is, non-zero otherwise.
sharfah@starship:~> kill -0 1234
sharfah@starship:~> echo $?
0

sharfah@starship:~> kill -0 1234x
bash: kill: 1234x: no such pid
sharfah@starship:~> echo $?
1
For those interested, the kill -l command lists signal numbers and names, but 0 is not listed.
sharfah@starship:~> kill -l
 1) SIGHUP     2) SIGINT      3) SIGQUIT   4) SIGILL
 5) SIGTRAP    6) SIGABRT     7) SIGEMT    8) SIGFPE
 9) SIGKILL   10) SIGBUS     11) SIGSEGV  12) SIGSYS
13) SIGPIPE   14) SIGALRM    15) SIGTERM  16) SIGUSR1
17) SIGUSR2   18) SIGCHLD    19) SIGPWR   20) SIGWINCH
21) SIGURG    22) SIGIO      23) SIGSTOP  24) SIGTSTP
25) SIGCONT   26) SIGTTIN    27) SIGTTOU  28) SIGVTALRM
29) SIGPROF   30) SIGXCPU    31) SIGXFSZ  32) SIGWAITING
33) SIGLWP    34) SIGFREEZE  35) SIGTHAW  36) SIGCANCEL
37) SIGLOST

Friday, July 25, 2008

SSH Without a Password

I often have to login to many different servers and hate having to type my password in everytime. What's even worse, is that I can't even cron up any nice scripts which use the SSH or SCP commands, because they would just hang asking for a password!

SSH works by the exchange and verification of information, using public and private keys, to identify hosts and users. It then provides encryption of subsequent communication, also by the use of public/private key cryptography. This post will show you how you can generate a public/private key pair, install them in the correct location and SSH without being prompted for a password.

Here are the steps involved:

1. Generate the public/private keys on the Client
First you have to generate a public/private key pair on the client, which is the machine you will be ssh'ing from. To do this, use the ssh-keygen command:

sharfah@starmobile:~> ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/sharfah/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/sharfah/.ssh/id_dsa.
Your public key has been saved in /home/sharfah/.ssh/id_dsa.pub.
The key fingerprint is:
d1:98:9d:8b:7d:f6:c1:ba:1d:cc:05:ee:0b:9d:2d:17 sharfah@starmobile
Now, if you look in your ~/.ssh directory, you will see two files:
  • id_dsa (the private key)
    -----BEGIN DSA PRIVATE KEY-----
    MIIBugIBAAKBgQDBDQ/+YpRikQfo/1x1mXRy83wbLJ67hUm357Vy24ab17V1FThm
    3S14D0UoqcTN0uflDLjj3CtfGeMU85t7Kbf1DBaiQ55syPilVqzQTjpuN44A3j5K
    e1eRX6LK46lspGR/ylrVHCRxJGXZ4K1OsxPgN7RhRHlRSOs5QAGeSAsHBQIVAJU1
    lempGnCjsaPop1BiYPvRoh4NAoGAI6qObsda+DnV3qQVHmV//iThpY3Z+z81uyUF
    1qq6XRnOTIwqJuF4lm0VBb4G+8pWIn3y5Kc+051sZ+gKlHcmtLMpxh+6QVD5KoRg
    XWHW11KEQldK9TKr18Taw8AhWFvp++kOd4I2Eq287Lecr95ty8YfdXD78kS+skpa
    z7/OdhkCgYAIXN2ljv5J1XAeZDnCfOPKkxWRoJ7M4/aKqdMIHAlxp6btpCuCl2cz
    F2/e0QQHUvABWjJpFG6IUNxRxDmvOinorfXR42thOFs4pNGMUWxVS4rRTYDpRGBz
    YbuY8awyzp2rAS6uhoHbpbDjsXhAA+fOJ0Xy6mJhDsj9Hnte5OD6DAIUBD2sJqrp
    ya/kd8vZSFrepLioucY=
    -----END DSA PRIVATE KEY-----
    
  • id_dsa.pub (the public key)
    ssh-dss AAAAB3NzaC1kc3MAAACBAMEND/5ilGKRB+j/XHWZdHLzfBssnruFSbfntXLbhpvXtXUVOGbdLXgPRSipxM3S5+UMuOPcK18Z4xTzm3spt/UMFqJDnmzI+KVWrNBOOm43jgDePkp7V5FfosrjqWykZH/KWtUcJHEkZdngrU6zE+A3tGFEeVFI6zlAAZ5ICwcFAAAAFQCVNZXpqRpwo7Gj6KdQYmD70aIeDQAAAIAjqo5ux1r4OdXepBUeZX/+JOGljdn7PzW7JQXWqrpdGc5MjCom4XiWbRUFvgb7ylYiffLkpz7TnWxn6AqUdya0synGH7pBUPkqhGBdYdbXUoRCV0r1MqvXxNrDwCFYW+n76Q53gjYSrbzst5yv3m3Lxh91cPvyRL6ySlrPv852GQAAAIAIXN2ljv5J1XAeZDnCfOPKkxWRoJ7M4/aKqdMIHAlxp6btpCuCl2czF2/e0QQHUvABWjJpFG6IUNxRxDmvOinorfXR42thOFs4pNGMUWxVS4rRTYDpRGBzYbuY8awyzp2rAS6uhoHbpbDjsXhAA+fOJ0Xy6mJhDsj9Hnte5OD6DA== sharfah@starmobile
    

2. Copy the public key to the Server(s)
Next, copy your public key, id_dsa.pub, to the server's authorized_keys2 file. The server is the machine you will be ssh'ing to. You can do this by editing the authorized_keys2 file on the server directly (not recommended) or with the one line command below, which appends the public key to the end of the authorized_keys2 file:

sharfah@starmobile:~/.ssh> cat id_dsa.pub | \
 ssh sharfah@starserver "cat >> ~/.ssh/authorized_keys2"
That's it! You can now SSH onto the server without being prompted for a password!

Friday, May 30, 2008

Increase Console Output in Eclipse [Howto]

By default, Eclipse limits the amount of text in the console output window. So if you are running a program which produces a lot of output, the Console will only display the last n lines and you lose the rest.

Here is a tip which will allow you to have unlimited output in the console:
  • Go to Window > Preferences > Run/Debug > Console
  • Uncheck "Limit Console Output" (Alternatively you can increase the Console buffer size.)

Friday, April 18, 2008

Garbage Collection Performance Tips

The purpose of Java's Garbage Collector is to find and reclaim unreachable objects. This post will show you how you can write readable and clean code that makes the most out of the garbage collector (in terms of throughput, responsiveness etc)
  • Do not be afraid to allocate small objects for intermediate results. Typically, object allocation is very cheap and reclamation of new objects is very cheap too! GCs love small, immutable objects and generational GCs love small, short-lived objects. You should use short-lived immutable objects instead of long-lived mutable ones. Use clearer, simpler code with more allocations instead of more obscure code with fewer allocations.

  • Avoid large objects as they are expensive to allocate and initialise.

  • Nulling references rarely helps the GC. Instead it creates clutter and in the worst case may introduce a bug. The JIT can do liveness analysis very well.

  • Avoid explicit GCs. Applications do not have enough information, but GC does. Calling System.gc() at the wrong time, may start a full stop-the-world GC (in HotSpot) which can hurt performance with no benefit.

  • Avoid frequent resizing of array-based data structures as this will allocate several large-ish arrays and will cause a lot of array copying. Try to size them, on initialisation, as realistically as possible.

  • Only use object pools for objects that are expensive to allocate/initialise or for those that represent scarce resources e.g. database connection pools or thread pools. Use existing libraries wherever possible. Unused objects in pools are bad; they are live and so the GC must process them and they provide no benefit to the application.

  • Use finalization as a last resort. Finalizable object allocation is much slower and reclamation takes at least two GC cycles; the first cycle identifies object as garbage and enqueues object on finalization queue, the second cycle reclaims space after finalize() completes. Finalizers are not like C++ destructors! There is no guarantee if or when they will be called.

  • Memory leaks occur because objects are reachable but unused. This may be due to objects in the wrong scope, lapsed listeners, exceptions changing control flow, instances of inner classes, reference objects etc. You should perform reachability analysis to clear up these objects.

Wednesday, December 05, 2007

Connect to AOL Broadband Without Their Application

When you subscribe to AOL Broadband, you are forced to install a resource intensive application (AOL8.0 or AOL9.0) and connect to the internet from there. I have noticed that this application (waol.exe) sometimes uses upto 99% CPU and my computer grinds to a halt!

In order to avoid having to use the AOL application and connect directly to the internet, follow the following steps:
  • Go to Control Panel and select Network Connections
  • Click New Connection Wizard
  • Choose to "Connect to the Internet" and then press Next
  • Choose to "Set up my connection manually" and then press Next
  • Choose to "Connect using a broadband connection that requires a user name and password" and then press Next
  • Type the name of your ISP e.g. "AOL Broadband" and then press Next
  • Choose for "Anyone's use" and then press Next
  • Type your User name e.g. "JohnSmith@aol.com", Password, Confirm password and then press Next
  • Tick "Add a shortcut to this connection to my desktop" and click Finish to close the wizard.
Now you can connect straight to the internet by going to your desktop and clicking on the "AOL Broadband" icon.

In order to automatically connect whenever you startup your computer, add this icon to the Startup folder:
C:\Documents and Settings\All Users\Start Menu\Programs\Startup

Monday, March 26, 2007

Windows XP Performance Tips

WINDOWS DISK INDEXING
This is a performance tip that I strongly recommend you implement. The Windows Disk Indexer constantly indexes all files on your machine to allow for faster searching using the Windows Search function for example. Since most people don't search their machine very often, having Disk Indexing enabled provides a performance hit for no good reason, and also increases fragmentation. Follow these steps to turn off the Windows Disk Indexer to improve hard drive performance and responsiveness:
1. Go to Windows Explorer, right-click on your hard drive name (e.g. C:) and select Properties.
2. Untick the 'Allow Indexing Service to index this disk for fast file searching'.
3. Select 'Apply changes to [Drive letter]\, subfolders and files' in the subsequent prompt.
4. Your system will now go through and remove all indexing on existing files, and not index any new or moved files in the future - this will speed up drive read/writes and general responsiveness. Ignore any 'errors' which are shown, this occurs simply because some files are in use or protected and can't have their properties changed to remove indexing - this is normal.

Make sure you also disable the 'Indexing Service' service as it is no longer necessary when disk indexing is removed from your hard drive.

DEFRAGMENTATION
I strongly suggest you get into the habit of defragmenting often, specifically after you delete or add large files or install software.

PREFETCH
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory
Management\PrefetchParameters]
EnablePrefetcher=3

I personally leave the Prefetcher registry setting above at its default of 3, and set the Task Scheduler service to Disabled. This means the prefetcher won't create application prefetch files under the Window\Prefetch directory. I also clear all out existing prefetch (.PF) files in that directory. I have found that this provides for the fastest Windows bootup time.

CONTROL PANEL > SYSTEM

> ADVANCED > PERFORMANCE SETTINGS
For fastest performance, I recommend deselecting everything except 'Use visual styles on windows and buttons' and 'Use drop shadows for icon labels on the desktop'. That will reduce usage of system resources for graphical effects, while still retaining the majority of Windows XP's trademark appearance.

> ADVANCED > PERFORMANCE SETTINGS > ADVANCED > VIRTUAL MEMORY


This is where you can set the size of your pagefile. To determine the optimal pagefile size you should ideally see how much memory your most memory intensive programs use and then set the pagefile to comfortably accommodate this.

Before setting a new pagefile size, first clear your existing pagefile. To do this select the 'No Paging File' option and click the Set button, then reboot your system. This step does two things: first it deletes the pagefile, fixing any potential pagefile corruption which can occur after a bad shutdown (remember this tip for future troubleshooting purposes); and secondly it ensures that any new pagefile you create will start off as a single unfragmented contiguous block on your hard drive for optimal performance, which will remain unfragmented in the future. Note that if you have any problems booting up into Windows due to a lack of a pagefile during this step, enter Windows in Safe Mode (See Backup & Recovery section) and continue the setup procedures for Virtual Memory from there.

Here is a simple general recommendation which is both safe to use on all systems, regardless of how much RAM you have, and provides good performance:
Set the Initial and Maximum pagefile sizes to 2560MB each - i.e. allocate 2.5GB for the pagefile. Whatever you do, don't set a zero pagefile.

> ADVANCED > STARTUP & RECOVERY SETTINGS
For a system with a single operating system, select '"Microsoft Windows XP [Home/Professional]" /fastdetect' in the list presented. If you only have one operating system, or you don't want to select a different operating system each time you boot up, untick the 'Time to display list of Operating Systems' option.

Under the 'System failure' section untick all three options for optimal performance, and the 'Write Debugging Information' option should be set to None. That way if you run into problems you'll see the error displayed (usually a Windows Blue Screen of Death (BSOD) message) and your system won't automatically reboot. At the same time you won't get lots of logfiles and dumpfiles of the event cluttering up your hard drive.

> ADVANCED > ERROR REPORTING
Click the Error Reporting button and select 'Disable Error Reporting' and tick 'But notify me when critical errors occur'. This will prevent your system continually informing Microsoft of errors occurring on your system, but at the same time will still show you important system messages and errors for notification and troubleshooting purposes.

> REMOTE
I strongly recommend that you disable the available options in this section for security and performance reasons.

> AUTOMATIC UPDATES
I recommend 'Turn off Automatic Updates' and instead use the manual method of regularly checking the Windows Update site for updates.

> SYSTEM RESTORE
Turn off System Restore, as it can take up a great deal of disk space

CONTROL PANEL > SOUNDS & AUDIO DEVICES
Disable as many sounds as possible as they take up system memory by being loaded into RAM at startup.

CONTROL PANEL > FOLDER OPTIONS
Use Windows Classic Folders
Open each folder in the same window
Double-click to open an item
Under View, I recommend you tick the following options:
  • Display file size information in folder tips
  • Display simple folder view in Explorer's folder list
  • Display the contents of system folders
  • Display the full path in the address bar
  • Display the full path in the title bar
  • Do not cache thumbnails
  • Show hidden files and folders
  • Show Control Panel in My Computer
  • Show encrypted or compressed NTFS files in color
It is recommended that the rest are unticked for best performance and functionality.

MOUSE
  • untick pointer shadow
  • auto default dialog button jump
  • pointer precision

SCREENSAVER
I recommend you set the screen saver to None to prevent burn-in (permanent image imprinting)

DISABLE STARTUP PROCESSES
Go to Run > msconfig and then choose the Startup tab.
Examine the list and disable any items you do not want started when your computer boots e.g. ypager, iTunesHelper etc.

DISABLE SERVICES
Go to Run > services.msc and then disable the following:
  • .NET Runtime Optimization Service
  • ASP.NET State Service
  • Clipbook
  • Error Reporting Service
  • Fast User Switching Compatibility
  • IMAPI CD-Burning COM Service
  • Indexing Service
  • Infrared Monitor
  • Machine Debug Manager
  • NetMeeting Remote Desktop Sharing
  • Network DDE
  • Network DDE DSM
  • Network Location Awareness (NLA)
  • Performance Logs and Alerts
  • Portable Media Serial Number Service
  • QoS RSVP
  • Remote Desktop Help Session Manager
  • Remote Registry
  • Routing and Remote Access
  • Secondary Logon
  • Security Center
  • Smart Card
  • SSDP Discovery Service
  • TCP/IP NetBIOS Helper
  • Telnet
  • Terminal Services
  • Uninterruptible Power Supply
  • Volume Shadow Copy
  • WebClient
  • Windows CardSpace
  • Windows User Mode Driver Framework
  • Wireless Zero Configuration
  • WMI Performance Adapter

Sunday, January 21, 2007

Interview Tips

I've had a few people - interns and grads - applying to investment banks asking me about interviews. I've been through the whole interview process at various places when I first left university and am now involved in interviewing candidates for positions in investment banking technology.

There are a few routine questions which everyone asks, so you should prepare them beforehand. There are also lots of interview question and answer banks online where you can find really good sample answers to common questions. Just Google around. I will try to think of the questions that I have been asked over the years and will categorise them so that they are easier for you to prepare. I will try to give you as many tips as possible. But remember that what works for me may not work for you!


Opening

Greet the interviewer with a firm handshake and a smile. You will probably be nervous but try to stay relaxed, always be polite (e.g. accept a glass of water if offered), smile, make eye contact and pay attention to the questions. Sometimes I forget what the question was, halfway through the answer! Always give clear and concise answers. I also like to take a notebook and a pencil with me to the office. It looks professional, you can make notes while the interviewer explains the company and you can also jot down some questions to ask later. At first, the interviewer will ask you some harmless questions, but answer these nicely because these create the first impression:
  • Hello! How are you?
  • How was the journey? Did you find us easily?
  • Where do you come from?
  • One of my favourite things is to comment on the building (e.g. Nice building / office!) when the interviewer is walking me to the room. It is a nice ice breaker and opens the interviewer up.

Know the company


Interviewers always ask about the company. Research:
  • Core values / principles / morals
  • Company structure i.e. business divisions, hierarchy etc
  • News articles e.g press releases from the companies website or search for the company in Google News. This is important so that you can comment on something read in the company’s annual report, web page or latest news report.
  • You may also want to read about other companies in the same field and update yourself on what is happening currently in this field even though it may not be related to the company you are applying to.
  • Why did you choose this company?
  • Have you heard about us in the news recently?

Know the industry

  • Learn banking jargon e.g. what is an investment bank, stock, bond, share, risk etc. (I was once asked to define an investment bank)
  • What are the main problems facing banks today?
  • Future of banking? (globalisation maybe? More mergers)

Know yourself

Be confident in your abilities and sell yourself! Keep in mind that there are hundreds of candidates applying and you need to make yourself stand out and be remembered.
  • Tell me about yourself (very open ended question: you have to give a brief history of your life including university, work, extracurriculars)
  • Why do you want to work in IT? (be passionate e.g. I like the rapid pace of change of this field, you can’t predict where it will go in the future; I love learning new cutting edge technologies)
  • Why should we hire you? (Sell yourself with lots of keywords: ambitious, energetic, adaptive, versatile, juggle multiple priorities, enthusiastic, an agent of change, I like to be stretched and challenged, I’m the best!)
  • What motivates you? (self motivated, recognition, good work atmosphere, work colleagues etc but NOT money)
  • Why did you choose to do a Masters in this degree?
  • Why did you choose a bank and not an IT company? (I’m interested in the financial world too)
  • What are your short / long term goals in life?
  • What are your strengths / weaknesses? (Strengths: flexibility, teamwork Weaknesses: Everyone has weaknesses, don't say you don't have any! Say how you combat your weakness. e.g. I get nervous during presentations but I always prepare well beforehand)
  • How do you measure your success?
  • How important is money to you? (not very)
  • What are your extra curricular activities?
  • What are you passionate about?
  • Work experience

Team Work


Companies are looking for team players, so expect lots of questions on team work.
  • Describe a project
  • What was your role in the team?
  • How do you handle conflicts?
  • What makes a good team? (a good balance of characters)
  • Desribe a situation in which others in the team did not agree with you. How did you persuade them to see things from your perspective?
  • Describe something that went wrong or a wrong decision you made and what you learned from your mistakes? (Everyone makes mistakes but you have to say what you learnt from them and how they made you stronger)
  • Are you a team player or do you enjoy individual research?
  • How do you handle multiple jobs with conflicting deadlines?

Know the Technology

You have to be well-versed in various technologies especially for a technical interview. Common questions are asked on:
  • Java (especially Threading and Collections)
  • XML / XSLT
  • Web Services and Technologies (e.g. .NET, SOAP)
  • UNIX vs Windows
  • Databases - SQL and Oracle
  • Security issues (e.g. in Wireless Networks)
  • E-Commerce and e-banking
  • .NET vs J2EE
  • What factors would you consider in choosing a programming language (e.g. Java or C++)?
  • Recent Viruses (e.g. Slammer had a big effect)
  • Outsourcing (most banks do it)
  • UML
  • Open Source
  • Up and coming technologies that will have a big impact in the future e.g. AJAX, Ruby, Linux
  • Read recent tech news items - check out my del.ici.ous page for technology links

Brain Busters

These questions are asked in order to find out whether you are able to think quickly and under pressure. I hate them! The trick is to keep talking about what you are thinking / reasoning. Do not sit quietly while you try to solve the question in your head. The ones I got were:
  • If you were an animal what animal would you be and why?
  • What is the cube root of 81?
  • How many tennis balls were used in the Wimbledon Men’s Singles tournament?
  • How many pennies can you fill in this room?
  • Why are man-hole covers round? (so that they don't fall in)

Closing

I know that you will be relieved when the interview is over, but do NOT run away quickly. Stay relaxed and thank the interviewer for his/her time. Say that you enjoyed talking to him/her and have learnt a great deal about the company and that you would love to work there. Its always good to have some questions to ask. I have found that interviewers like to be asked questions about themselves! Be nosy about their life:
  • How did you end up working here?
  • What do you like most about working here?

If you have their email address send them a thank-you email as soon as you get home.

Good luck with the interview and if you have any further questions, don't hesitate to ask me!

Tuesday, November 07, 2006

My Bash Profile

Bash is my favourite shell and here is my .bashrc which has grown substantially over the years as I have added (and will continue to add) more and more useful aliases and functions. These are very useful because they save time and also stop you from having to type in long error-prone commands.

My personal favourite alias is ll='ls -ltr' and I don't understand why some people still type in the long form for such a common command.



###############################
# FAHD SHARIFF'S BASH PROFILE #
###############################

HISTCONTROL=ignoredups
EDITOR=emacs

set -o notify
set -o braceexpand
set -o emacs

##########
# PROMPT #
##########

PS1=\[\e[0m\]\e]2;\u@\h:`tty`>\w[\d,\t]\a\n\[\e[4;34;1m\]\u@\h:\[\e[0;31;1m\]\w>\[\e[m\]

###############
# COMPLETIONS #
###############

shopt -s extglob progcomp cdspell

# Make directory commands see only directories
complete -d cd mkdir rmdir pushd jd

# Make file commands see only files
complete -f cat less more chown ln strip nedit emacs

complete -f -X '!*.@(zip|ZIP|jar|JAR|exe|EXE|pk3|war|wsz|ear|zargo|xpi)' unzip zipinfo
complete -f -X '*.Z' compress
complete -f -X '!*.@(Z|gz|tgz|Gz|dz)' gunzip zcmp zdiff zcat zegrep zfgrep zgrep zless zmore
complete -f -X '!*.Z' uncompress
complete -f -X '!*.@(gif|jp?(e)g|tif?(f)|pn[gm]|p[bgp]m|bmp|xpm|ico|xwd|tga|pcx|GIF|JP?(E)G|TIF?(F)|PN[GM]|P[BGP]M|BMP|XPM|ICO|XWD|TGA|PCX)' ee display
complete -f -X '!*.@(gif|jp?(e)g|tif?(f)|png|p[bgp]m|bmp|x[bp]m|rle|rgb|pcx|fits|pm|GIF|JPG|JP?(E)G|TIF?(F)|PNG|P[BGP]M|BMP|X[BP]M|RLE|RGB|PCX|FITS|PM)' xv qiv
complete -f -X '!*.@(ps|PS)' gv ggv
complete -f -X '!*.@(ps|PS|pdf|PDF)' fmerge
complete -f -X '!*.@(dvi|DVI)?(.@(gz|Z|bz2))' xdvi
complete -f -X '!*.@(dvi|DVI)' dvips dviselect dvitype
complete -f -X '!*.@(pdf|PDF)' acroread gpdf xpdf
complete -f -X '!*.texi*' makeinfo texi2html
complete -f -X '!*.@(?(la)tex|?(LA)TEX|texi|TEXI|dtx|DTX|ins|INS)' tex latex slitex jadetex pdfjadetex pdftex pdflatex texi2dvi
complete -f -X '!*.fig' xfig
complete -f -X '!*.@(?([xX]|[sS])[hH][tT][mM]?([lL]))' netscape mozilla lynx appletviewer hotjava
complete -f -X '!*.tar' tar
complete -f -X '!*.java' javac
complete -f -X '!*.idl' idl idlj

# user commands see only users
complete -u su usermod userdel passwd write groups w talk

# bg completes with stopped jobs
complete -A stopped -P '%' bg

# other job commands
complete -j -P '%' fg jobs disown

# readonly and unset complete with shell variables
complete -v readonly unset

# set completes with set options
complete -A setopt set

# shopt completes with shopt options
complete -A shopt shopt

# unalias completes with aliases
complete -a unalias

# type and which complete on commands
complete -c command type which

# complete hostnames
complete -A hostname ssh telnet rlogin ftp ping traceroute

###########
# ALIASES #
###########

alias ..=cd ..
alias ...=cd ../..
alias ....=cd ../../..
alias .....=cd ../../../..

alias cl=clear
alias cla=clear;la
alias cll=clear;ll
alias cls=clear;ls
alias clal=clear;lal

alias rmdir=rm -rf

alias d=date
alias ff=find . -name $1
alias h=history

alias l=ls
alias la=ls -a
alias ll=ls -ltr
alias lal=ls -al
alias ls=ls -F
alias sl=ls

alias more=less
alias mroe=more
alias m=more

alias r=fc -s
alias igrep=grep -i

#############
# FUNCTIONS #
#############

#kill a process by name
pskill()
{
if [ -z $1 ]; then
echo -e \e[0;31;1mUsage: pskill [processName]\e[m;
else
ps -au $USER | grep -i $1 |awk {print kill -9 $1}|sh
fi
}

#jump to a directory
jd()
{
if [ -z $1 ]; then
echo -e \e[0;31;1mUsage: jd [directory]\e[m;
else
findresults=( $(find . -type d -name $1) )
count=${#findresults[@]}
if [ $count = 1 ]; then
file=${findresults[0]}
cd $file
else
if [ $count = 0 ]; then
echo No such directory
else echo Ambiguous: $count directories found
fi
fi
unset findresults
unset count
fi
}

#display directory tree structure
tree()
{
echo -e \033[1;35m

(cd ${1-.} ; pwd)
find ${1-.} -print | sort -f | sed \
\
-e s,^${1-.},, \
-e /^$/d \
-e s,[^/]*/\([^/]*\)$,\ |-->\1, \
-e s,[^/]*/, | ,g

echo -e \033[0m
}

#mkdir and cd combined
mkcd()
{
if [ -z $1 ]; then
echo -e \e[0;31;1mUsage: mkcd [directory]\e[m;
else
if [ -d $1 ]; then
echo Changed to $1.;
cd $1;
else
mkdir $1;
echo Created $1;
cd $1;
fi;
fi
}

#######
# END #
#######

mesg -n
echo -e \e[0;31;1m$USER logged in to `tty` on `date`\e[m