特定のパスで指定されたコマンドを実行し、現在のパスに戻るコマンドを実装します。

特定のパスで指定されたコマンドを実行し、現在のパスに戻るコマンドを実装します。

私のコード:

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

$ path ~ ls提供:( bash: cd: prev_dir: No such file or directory および私のホームディレクトリの古いファイル)

ベストアンサー1

"$prev_dir"参照変数を使用する必要がありますprev_dir

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

alias path=execInPath

しかし、サブシェルを使用する方が簡単です。

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

alias path=execInPath

おすすめ記事