0

my code:

execInPath() {
prev_dir=${PWD##*/}
cd $1
shift
res=$($@)
cd prev_dir
echo res
}
alias path=execInPath

$ path ~ ls gives: bash: cd: prev_dir: No such file or directory (and the files in my home directory prior to that)

3 Answers3

3

You must use "$prev_dir" to reference variable prev_dir:

execInPath() {
  prev_dir=${PWD##*/}
  cd -P -- "$1"
  shift
  res=$( "$@" )
  cd -- "$prev_dir"
  printf '%s\n' "$res"
}

alias path=execInPath

But using a subshell is easier:

execInPath() {
  : 'Change directory in subshell'
  (
    cd -- "$1" || return 1
    shift
    res=$( "$@" )
    printf '%s\n' "$res"
  )
  : 'Back to previous dir'
  pwd
}

alias path=execInPath
cuonglm
  • 150,973
  • 38
  • 327
  • 406
3

Use a subshell:

execInPath() (cd -P -- "$1" && shift && exec "$@")

Notes:

  • You need to check the exit status of cd as if cd fails, you'd run the command in the wrong directory.
  • if you want cd to behave like in other languages, you need -P.
  • think of the exit status of your function. Here, you want it to be unsuccessful if cd fails, and be the exit status of "$@" otherwise.
  • $@ must be quoted always.
  • It's impossible to do cd some-dir;...;cd original-dir and get back to the same original directory 100% reliably.
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
1

When you assign a variable in bash, there is no $ (unlike perl), but when you use/refer to a variable in bash, you need to add the $ to it. Your cd prev_dir should be cd $prev_dir.

Tim S.
  • 359
  • 3
  • 13
  • `cd $prev_dir` doesn't make sense. It should be at least `cd "$prev_dir"` or rather `cd -P -- "$prev_dir"`. – Stéphane Chazelas Feb 02 '16 at 17:10
  • Not sure why it doesn't make sense. The quotes are not required. `export prev_dir="/bin";cd $prev_dir` works just fine. – Tim S. Feb 02 '16 at 17:18
  • @TimS.: See http://unix.stackexchange.com/q/171346/38906 and http://unix.stackexchange.com/q/131766/38906 – cuonglm Feb 02 '16 at 17:22
  • See [Security implications of forgetting to quote a variable in bash/POSIX shells](http://unix.stackexchange.com/q/171346), [Why does my shell script choke on whitespace or other special characters?](http://unix.stackexchange.com/q/131766), [When is double-quoting necessary?](http://unix.stackexchange.com/q/68694), [Expansion of a shell variable and effect of glob and split on it](http://unix.stackexchange.com/q/108963), [Quoted vs unquoted string expansion](http://unix.stackexchange.com/q/78914)... – Stéphane Chazelas Feb 02 '16 at 17:24
  • While I agree that it's a security issue, that's far from "doesn't make sense". Personally I don't use bash for a number of reasons, but that's beside the point. Thanks for the links. – Tim S. Feb 02 '16 at 17:56
  • It makes as little sense as writing `chdir(glob(split($prev_dir)))` in another language. The equivalent of `chdir($var)` is `cd -P -- "$var"` (except when `$var` contains `-`). – Stéphane Chazelas Feb 02 '16 at 21:38