46
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

dirname $0 でスクリプト置いてあるディレクトリにならない

Posted at

シェルスクリプトでどこからスクリプト叩いても同じ動作するように

cd `dirname $0`

をよく使うが、cd 実行後に相対パスで実行するとスクリプトの配置ディレクトリに移動してくれなくなる

smple.sh
#!/bin/bash

cd `dirname $0`
echo "`pwd` \n"

cd /usr/local
echo "`pwd` \n"

cd `dirname $0`
echo "`pwd` \n"
実行結果
[16:26:36 tmp]$ pwd
/tmp
[16:26:58 tmp]$ sh sample.sh 
/tmp 

/usr/local 

/usr/local 

[16:27:03 tmp]$ sh /tmp/sample.sh 
/tmp 

/usr/local 

/tmp 

[16:27:09 tmp]$

$0(コマンド)のdirnameなので当たり前といえば当たり前ですが、結構はまった

46
49
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?