Mark Needham

Thoughts on Software Development

Browsing around the Unix shell more easily

with 14 comments

Following on from my post about getting the pwd to display on the bash prompt all the time I have learnt a couple of other tricks to make the shell experience more productive.

Aliases are the first new concept I came across and several members of my current team and I now have these setup.

We are primarily using them to provide a shortcut command to get to various locations in the file system. For example I have the following ‘work’ alias in my ~/.bash_profile file:

alias work='cd ~/path/to/my/current/project'

I can then go to the bash prompt and type ‘work’ and it navigates straight there. You can put as many different aliases as you want in there, just don’t forget to execute the following command after adding new ones to get them reflected in the current shell:

. ~/.bash_profile

A very simple idea but one that helps save so many keystrokes for me every day.

Another couple of cool commands I recently discovered are pushd and popd

They help provide a stack to store directories on, which I have found particularly useful when browsing between distant directories.

For example suppose I am in the directory ‘/Users/mneedham/Desktop/Blog/’ but I want to go to ‘/Users/mneedham/Projects/Ruby/path/to/some/code’ to take a look at some code.

Before changing to that directory I can execute:

pushd .

This will push the current directory (‘/Users/mneedham/Desktop/Blog/’) onto the stack. Then once I’m done I just need to run:

popd

I’m back to ‘/Users/mneedham/Desktop/Blog/’ with a lot less typing.

Running the following command shows a list of the directories currently on the stack:

dirs

I love navigating with the shell so if you’ve get any other useful tips please share them!

Written by Mark Needham

October 15th, 2008 at 10:31 pm

Posted in Shell Scripting

Tagged with

  • Pingback: UNIX Coding School » Blog Archive » unix tips [2008-10-15 12:58:57]

  • http://www.rickumali.com/ Rick Umali

    An alternative to aliases is BASH’s “cdable_vars” feature. Enable this with the shopt command in BASH. This allows you to create variables that contain paths (e.g. mydir=/home/rick), which you can then cd into (e.g. cd mydir). Yet another way to do the same thing. I enjoy reading your posts!

  • http://blogbysud.blogspot.com sud

    One of my favorites which I picked up from a co-worker is the recall facility in a Unix shell.

    Here is a link that explains this and saves keys strokes like no other.

    http://techie-buzz.com/linux-tips/how-to-recall-typed-commands-in-linux.html

  • Dave Kirby

    Try zsh as an alternative to bash. It has all the features of bash, plus some extras that make life so much easier. For example:

    Extended file globbing. e.g. ** will expand through all the subdirectories, you can do case insensitive matches, OR matches, match files and remove the extension, and so on. So “ls **/*.(java|(#i)xml)” will list all files in the current directory and all subdirectories with the extension java or xml (where xml is case insensitive). I use the ** feature all the time, and hardly ever have to use the ‘find’ command.

    As well as supporting the search facility that sud mentioned, you can also have a mode where you type the first few characters of a line in your history, then can cycle through the lines that start with those characters. I find this much more natural than searches. I have this bound to the and keys, since that is what I am used to in Vim.

    Smart Completion. zsh not only knows about filenames but also about commands. So for example (if you have enabled it) type “svn ” to list all the svn subcommands, or “ls -” to list all the options to ls. You can add your own smart completions for new commands.

    There are lots and lots of other features (I am still learning about them), but IMHO the ** directory expansion alone is reason enough to switch. Zsh is in most linux repositories and cygwin. You can find out more at http://zsh.dotsrc.org/.

  • Dave Kirby

    Damn, the comment system stripped out my text in angle brackets – that should be “svn TAB” and “ls -TAB” in the penultimate paragraph, and CTRL-N and CTRL-P to move through the history.

  • Wirianto Djunaidi

    Another quick one if you don’t want to bother with popd and pushd is to use “cd -” to go to the last directory you were from. Of course this does not work if you traverse your directory one by one manually most of the time. It can be useful if you jump to other directory faraway by using “cd /xyz/abc/def/fda/kfjd”, once you are finish by typicng “cd -” it will bring you back to your original directory.

  • http://jroller.com/wipu Ville Oikarinen

    I use another strategy: I don’t try to make it easier to cd, I remove the need by dedicating one terminal window for one task.

    The shade feature of openbox (many other windowmanagers support it, too) helps here, because I can keep most of the terminals shaded, and the cwd is visible in the title bar so I know which terminal to unshade when I need to do any particular task.

  • http://billcomer.blogspot.com/ Bill Comer

    I have always been a fan of pushd/popd/dirs

    I use the following:

    alias cdh=”dirs -v”
    alias cd=”pushd”
    alias cd-=”popd”
    alias cd–=”popd;popd”
    alias cd—=”popd;popd;popd”

    alias up2=”cd ../..”
    alias up3=”cd ../../..”

    I also like to use:
    alias ll=”ls -lrt”
    and my all time favourite:
    alias lds=”ls-l | grep ^drw”

    Then
    cd ~1 #will take you to the dir at position 1 in the stack
    cd #rotates the stack. NB default cd is to take you to home directory

  • http://muness.blogspot.com Muness Alrubaie

    Check out http://muness.blogspot.com/2008/06/lazy-bash-cd-aliaes.html for a script that makes creating these aliases easier to create: you only have to specify the parent directory that has all your projects and it creates aliases for all of them.

  • Pingback: Tweets that mention Browsing around the Unix shell more easily at Mark Needham -- Topsy.com

  • MGF

    Bash has the ‘**’ wild card capability, under ‘shopt’:

    globstar
    If set, the pattern ** used in a pathname expansion
    context will match a files and zero or more directories and subdirectories.
    If the pattern is followed by a /, only directories and subdirectories match.

  • MGF

    pushd and popd are useful. However, it is too bad that bash does not have the ‘dunique’ option setting, which ensures that duplicate entries are removed from the directory stack when using ‘pushd’ to navigate to a new directory. This can of course be handled by defining ‘cd’, ‘pushd’, ‘popd’ function re-implementations.

    Also, although file name completion is defined for ‘cd’, it is not defined for pushd (in /etc/bash_completion). This can be remedied by something like the following:


    eval `complete -p cd 2>/dev/null | sed -e 's/ cd\$/ pushd/'`

  • MGF

    Another useful command line recall and editing feature is the ‘fc’ builtin:


    $ help fc
    fc: fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command]
    Display or execute commands from the history list.

    fc is used to list or edit and re-execute commands from the history list.
    FIRST and LAST can be numbers specifying the range, or FIRST can be a
    string, which means the most recent command beginning with that
    string.

    Options:
    -e ENAME select which editor to use. Default is FCEDIT, then EDITOR,
    then vi
    -l list lines instead of editing
    -n omit line numbers when listing
    -r reverse the order of the lines (newest listed first)

    With the `fc -s [pat=rep ...] [command]' format, COMMAND is
    re-executed after the substitution OLD=NEW is performed.

    A useful alias to use with this is r='fc -s', so that typing `r cc'
    runs the last command beginning with `cc' and typing `r' re-executes
    the last command.

    Exit Status:
    Returns success or status of executed command; non-zero if an error occurs.

  • MGF

    And on the topic of shell options that when enabled can save typing, here are a few, including the cdable_vars option, mentioned earlier:


    autocd
    If set, a command name that is the name of a directory
    is executed as if it were the argument to the cd com-
    mand. This option is only used by interactive shells.

    cdable_vars
    If set, an argument to the cd builtin command that is
    not a directory is assumed to be the name of a variable
    whose value is the directory to change to.

    cdspell
    If set, minor errors in the spelling of a directory component in a cd command will be corrected. The errors
    checked for are transposed characters, a missing character, and one character too many. If a correction is
    found, the corrected file name is printed, and the command proceeds. This option is only used by interactive
    shells.

    cmdhist
    If set, bash attempts to save all lines of a multiple-
    line command in the same history entry. This allows
    easy re-editing of multi-line commands.

    dirspell
    If set, bash attempts spelling correction on directory
    names during word completion if the directory name
    initially supplied does not exist.
    dotglob If set, bash includes filenames beginning with a ‘.’ in
    the results of pathname expansion.

    histreedit
    If set, and readline is being used, a user is given the
    opportunity to re-edit a failed history substitution.

    histverify
    If set, and readline is being used, the results of his-
    tory substitution are not immediately passed to the
    shell parser. Instead, the resulting line is loaded
    into the readline editing buffer, allowing further modi-
    fication.

    hostcomplete
    If set, and readline is being used, bash will attempt to
    perform hostname completion when a word containing a @
    is being completed (see Completing under READLINE
    above).