bashaliascddirnamepositional-parameter

In Bash scripting, how to change directory to a file's directory path using the function `dirname`?


I would like to change directory to that of a file by defining an alias:

alias direc=`cd | echo dirname "$1"`

but this doesnt work. Any ideas are appreciated for how I can restructure this.


Solution

  • You are going backwards. The result of dirname should be the argument to cd, rather than dirname trying to use the output of cd.

    Also, use a function instead of an alias.

    direc () {
      cd "$(dirname "$1")"
    }