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
  • 153,898
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.
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