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)

1
  • cd $prev_dir instead of cd prev_dir; maybe also echo $res Commented Feb 2, 2016 at 16:51

3 Answers 3

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
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.
3
  • This also came into my mind at first, but it seems that the OP want to do other things inside function after go back to previous dir. Commented Feb 2, 2016 at 17:13
  • Would you mind explaining more details about behave like in other languages, what's other languages? Commented Feb 2, 2016 at 17:14
  • @cuonglm, the chdir or C, perl, python, ruby, java, you name it. Commented Feb 2, 2016 at 17:25
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.

6

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.