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 between 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 the [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 by 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 the directory by replacing a part of the current path. For example, if you wish to change the 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

Share this post

Comments (0)

    No comment

Leave a comment

All comments are moderated. Spammy and bot submitted comments are deleted. Please submit the comments that are helpful to others, and we'll approve your comments. A comment that includes outbound link will only be approved if the content is relevant to the topic, and has some value to our readers.


Login To Post Comment