0

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.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
user321627
  • 2,350
  • 4
  • 20
  • 43
  • what is the use of this alias? It does exactly the same as dirname? Why not use 'dirname' directly? – Chris Maes Nov 06 '19 at 20:11
  • Hi, I actually would like to change directory to the directory of a file. This way I envision doing `direc path/to/file` to automatically change to it. I updated the question, my apologies – user321627 Nov 06 '19 at 20:13
  • 1
    Does this answer your question? [Make a Bash alias that takes a parameter?](https://stackoverflow.com/questions/7131670/make-a-bash-alias-that-takes-a-parameter) You cannot pass arguments to an alias, only to functions, but you can make an alias that calls a function if you so desire. – jeremysprofile Nov 06 '19 at 20:16

1 Answers1

1

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")"
}
chepner
  • 497,756
  • 71
  • 530
  • 681
  • I defined functions as `function direct{cd "$(dirname "$1")"}`. Is this equivalent to the above you have? – user321627 Nov 06 '19 at 20:28
  • 1
    Yes, but it uses non-standard syntax which has no real reason for existing in new. Use the standard form of function definition that I have shown. (My understanding is that the `function` keyword is allowed mainly to ease the use of code written for `ksh`, though I'm not even sure if `ksh` made any distinction between the two forms.) – chepner Nov 06 '19 at 20:33
  • @user321627 You need to add blanks and a semicolon: `function direct { cd "$(dirname "$1")"; }` or, as mentioned, `direct() { cd "$(dirname "$1")"; }` – Benjamin W. Nov 06 '19 at 20:44
  • (or with parameter expansion: `direct() { cd "${1%/*}"; }`) – Benjamin W. Nov 06 '19 at 20:46