Ksh/Bash Change Directory commands

When you're working in the command-line interface, you may be going deep inside the directories and moving back and forth those directories can be a nuisance. There are built-in directory commands in ksh/bash that you can use to ease your change directory (cd) pain.

How do you use Bash Auto Completion?

A: The file and directory name completion are available by default in bash. To use the default auto completion feature of bash, you'll hit [TAB] Key once or twice.

% ls
four   one   three   two
% ls o[TAB] will automatically match "one"
% ls t[TAB] will not match anything, pressing [TAB] once more will show more.
three   two

Q: How to change to a directory from replacing a part of the current path?

A: Ksh and Bash currently don't support this functionality by default, but creating a simple function will achieve this.

function cd()
{
if [ $# -eq 2 ]; 
then builtin cd ${PWD/$1/$2}; 
else builtin cd $1; fi 
}

Place this function in your ~/.bashrc, /etc/bashrc or /etc/profile, and you'll be able to change directory by replacing a part of the current path. For example, if you wish to change directory from /home/mary/public_html to /home/kevin/public_html, you'll perform the following command:

% cd /home/mary/public_html
% cd mary kevin
% pwd
/home/kevin/public_html

How to use pushd, popd and dirs built-in shell commands?

There are pushd, popd and dirs built-in shell commands that you can use to manipulate the directory stack. You may simply push or pop a directory from the directory stack provided by the shell.

Here is a practical example of using pushd, popd and dirs.

% cd /tmp/test/x
% pushd .
% cd ../y
% dirs
/tmp/test/y   /tmp/test/x
% popd
/tmp/test/x
% pwd
/tmp/test/x

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.