LoginSignup
3
3

More than 5 years have passed since last update.

内部で使われている特定のコマンドの挙動を変更してシェルスクリプトを実行する(例えばdateの結果を別の日に変えたり)

Last updated at Posted at 2015-12-23

背景

  • 昨日一日分のデータを集計するようなシェルスクリプトがあった
  • しかし過去数日の集計処理がエラー終了していたので、エラーになった日付を対象に再集計したかった
  • しかしそのシェルスクリプトは引数で日付を受け取るような仕様になっていなかった
    • 本来はここで引数を追加するべき
  • シェルスクリプト内部では昨日という日を得るためにdateコマンドを使用していた

対応策

  • dateという名前で関数を定義し、その内部では集計したい日を返す、そしてそれを export してからシェルスクリプトを実行した
$ bash -c 'function date() { echo "20150101"; }; export -f date; ./target.sh'
  • 上記であれば常に date20150101 を返す

検証

サンプルコード

parent.sh

#!/bin/bash

source ./functions.sh

echo "parent"
echo "yesterday is `getYesterday`"

./child.sh

child.sh

#!/bin/bash

source ./functions.sh

echo "child"
echo "yesterday is `getYesterday`"

functions.sh

#!/bin/bash

function getYesterday () {
    echo `date --date="yesterday" +"%Y%m%d"`
}

実行

今日の確認

$ date +"%Y%m%d"
20151223

普通に実行

$ ./parent.sh
parent
yesterday is 20151222
child
yesterday is 20151222

dateを上書いて実行

$ bash -c 'function date() { echo "20150101"; }; export -f date; ./parent.sh'
parent
yesterday is 20150101
child
yesterday is 20150101

注意!

  • もちろんそのコマンド(例ではdate)を使用している箇所すべてに影響が出るので、予想外の挙動になることもあり、あまりおすすめできない
    • こういうこともできるんだ〜という程度で
  • それと /bin/date のようにフルパスで指定されてるとこの技は使えない
3
3
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
3
3