1

Background:

This question is about using the cd command in a bash script or alias.

There is a related SO question here: Why doesn't "cd" work in a bash shell script?

Problem:

Suppose you have a bash program called "foopath" that sends a path to a directory to stdout when you pass in an argument, e.g.,

  $> /usr/bin/foopath 1998      ## returns /some/long/path/here/1998
  $> /usr/bin/foopath 80817     ## returns /totally/different/path/80817/files

The foopath program just does a lookup and returns the closest matching path it can find based on the argument the user passed in.

Question:

1) How would you construct a function and alias in your .bash_profile so that the user can:

  • 1a) type foo 1998 or foo 80817 (foopath command shortening goal)
  • 1b) change dir using cd foo 1998 or cd foo 80817 (change-directory goal)
  • 1c) change directory from the command prompt (not-just-subshell-only goal)

Pitfalls

Because of the goal in 1c above, this seemingly simple task is proving cumbersome. In other words, the function/alias should be usable interactively, just as shown in the example from the related SO post at Why doesn't "cd" work in a bash shell script?.

Community
  • 1
  • 1
dreftymac
  • 31,404
  • 26
  • 119
  • 182

2 Answers2

1

1a)

foo () {
    cd "$(foopath $1)"
}

1b)

cd () {
    case $1 in     
      (foo) builtin cd "$(foopath $2)";;
      (*)   builtin cd "$@";;
    esac
}

1c) Both 1a) and 1b) can be used interactively.

Jens
  • 69,818
  • 15
  • 125
  • 179
1

The solution could be either

  1. by making the script a function instead

    function script() 
    {
         cd "$(foopath "$*")"
    }
    
  2. by using source script.sh (or . script.sh) instead, so the script runs in the calling shell

sehe
  • 374,641
  • 47
  • 450
  • 633