Slow script execution after mocking system "date" command

时间:2019-04-08 13:23:14

标签: bash

Hellow fellow Stack users,

I am using a function "setup_date" to change date command for my custom execution. This is to mock it and test some bash scripts, their execution has to use always the same date in order to compare results.

So this approach worked very good with ssh or sftp command mocking. But this time, just after "date" command substitution, the script's execution becomes very slow! What is the reason for that? Is "date" command called frequently by linux system for internal uses?

Regards,

#
#replace a command with previousy defined mock one
#
mock_cmd() {
  local command="${1:-}"
  local override="${2:-}"

  # Remove target function if one is already set
  unset ${command}
  # Create a wrapper function called "${command}"
  eval "${command}() { ${override} \${@}; }"
}


#mock the date command
#1- date formatting
#There has to be a variable: dateFile!
date_mock_SP() {
    date "${1}" -r ${dateFile}
}


#
#1- date ex: 201203101513
#2- dateFile path
setup_date() {
    touch -t "${1}" ${2}/dateFile
    export dateFile=${2}/dateFile
}


EXECUTION : 

mock_cmd "date" "date_mock_SP"

setup_date "201203101513" ${pwd}/in

Date=$(date +"%y%j")
echo $Date

Date=$(date +"%y%j")
echo $Date

exit 1

1 个答案:

答案 0 :(得分:3)

mock_cmd is brittle and more complicated than you need. You are already defining the function date_mock_SP; just name it date, and the function will override the command. Inside the function, use command date to avoid infinite recursion.

date () { command date "$1" -r "$dateFile"; }

setup_date "201203101513" "$pwd/in"  # uses the function, not the executable, date

unset -f date