There is a function that runs the command passed to it.

function run() { OLD_PWD=`pwd` cd `dirname "${BASH_SOURCE[0]}"`/.. if "$@" then echo "GOOD" cd ${OLD_PWD} else colorecho 1 "Command <$@> failed ... exiting" cd ${OLD_PWD} exit 1 fi } 

It is necessary to insert the time utility in the launch of this command, that is, I am writing run mkdir -p /some/thing/dir , and under the hood /usr/bin/time -f "%C %E" mkdir -p /some/thing/dir is called /usr/bin/time -f "%C %E" mkdir -p /some/thing/dir , tell me how to do it?

    3 answers 3

    You can somehow like this:

     function run() { #... /usr/bin/time -f "%C %E" "$@" #... } 

    Of course, the GNU time must be set.

    In addition, instead of OLD_PWD I would advise using pushd / popd or subshell.

    • I didn’t understand how to insert it into the condition, could I show an example based on my code, otherwise I insert it and catch the error ./scripts/run.sh: line 29: /usr/bin/time -f "%C %E" @: No such file or directory - shotInLeg
    • @shotInLeg, what condition? ... yes, I missed $ in the command ... - Fat-Zer
    • I need to check the exit code of this process - shotInLeg
    • one
      @shotInLeg, you can directly substitute it in if , but can you put it in front of if, and then $? compare with zero ... - Fat-Zer

    So, probably:

     function run() { OLD_PWD=`pwd` TIME = `/some/thing/dir` cd `dirname "${BASH_SOURCE[0]}"`/.. run mkdir -p ${TIME} if "$@" then echo "GOOD" cd ${OLD_PWD} else colorecho 1 "Command <$@> failed ... exiting" cd ${OLD_PWD} exit 1 fi } 
    • the task is not to run something prered by executing the command, but to calculate the time of the transmitted command. run ls -l -> execute ls -l , and I want the run ls -l execute /usr/bin/time -f "%C %E" ls -l - shotInLeg

    I do not insist, but it works.

     run () { local retv pushd "$(pwd)" >/dev/null cd "${BASH_SOURCE[0]%/*}" source <(cat <<CODE /usr/bin/time -f '%C %E' $@ retv=$? CODE ) popd >/dev/null (( retv )) && \ { colorecho 1 "Command <<$@>> failed ... exiting" >&2 exit $retv } || echo 'GOOD' >&2 return 0 } run find /etc -type f -name '*tab' -exec cat {} '\;' '2>/dev/null'