コード日進月歩

しんくうの技術的な小話、メモ、つれづれ、など

bashのワンライナーでディレクトリをcdしたいときは -c を用いると簡単に実現できる

dockerやらなんやらで相対的にパスを扱いたいひとのためのワンライナー

環境

$ bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.

やりたいこと

cdをしたあとにコマンドを実行し、かつコマンドを実行したシェルはcdしたくない。

やりかた

-c オプションを使う、man曰く以下のような動き

If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

Google和訳すると

-cオプションが存在する場合、コマンドはstringから読み取られます。文字列の後に引数がある場合は、$0から始まる位置パラメータに割り当てられます。

ということで以下のコマンドで実現できる

$ pwd
/Users/watashi_user
$ sh -c "cd /tmp/; pwd"
/tmp
$ pwd
/Users/watashi_user

発展型

sudo -i をしたときでもできるのでAWS環境などでは便利

$ sudo -i sh -c "cd /tmp/;whoami; pwd"
root
/tmp

参考リンク