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?.

1
  • 1
    Please clarify 1c). Do you mean using the function/alias interactively? Commented May 13, 2013 at 11:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.