LoginSignup
19
19

More than 5 years have passed since last update.

sourceされたら何もしないで実行のみ可能なシェルスクリプトを作るワンライナー

Last updated at Posted at 2016-05-22

実行可能プログラムとして作成したシェルスクリプトが、何かの間違いで .source で読み込まれた時に想定外の動作をしてしまわないよう、source されること自体を禁止(何もしない)したいときは以下の様な1行を冒頭に書いておけば良い。

dont_source.sh
#!/bin/bash
return 1 2>/dev/null || true

echo "I am just a command"
  • . dont_source.sh された場合 return 1 によっていきなり処理は終了し、以降のコードは一切実行されない。
  • プログラムとして実行された場合 return 1 は必ず失敗し、そのまま何ごとも無かったかのように以降の行に処理が続きプログラムは継続する。また、set -e されているとエラーが発生した時点で終了されてしまうので、それを防ぐために || true でステータスコードを 0 にリカバリしている。
19
19
0

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
19
19