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)
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)
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
Use a subshell:
execInPath() (cd -P -- "$1" && shift && exec "$@")
Notes:
cd
as if cd
fails, you'd run the command in the wrong directory.cd
to behave like in other languages, you need -P
.cd
fails, and be the exit status of "$@"
otherwise.$@
must be quoted always.cd some-dir;...;cd original-dir
and get back to the same original directory 100% reliably.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
.
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
export prev_dir="/bin";cd $prev_dir
works just fine.
– Tim S.
Feb 02 '16 at 17:18
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
cd $prev_dir
instead ofcd prev_dir
; maybe alsoecho $res
– Jeff Schaller Feb 02 '16 at 16:51