Search code examples
linuxbashshelltimesh

How to Calculate Execution Time and Get Command Exit Code


I write a shell script and I want to get execution time of a command but I also redirect output of command to a file. Also, I need to get exit code of this specific command to use it in if statement. Here is what I have tried:

...
TIMEFORMAT=%R

log_file() {
  echo "$PROJECT_DIR/logs/$1_$(date +%Y%m%d_%H%M%S).log"
}    

CODE_TIME=$(time sh -c "ipython -c "%run ./foo.ipynb" > $(log_file "log_file_name") 2>&1")

CODE_RESULT=$?

echo "Code_Result: $CODE_RESULT"

if [ "$CODE_RESULT" -eq 0 ]

    ...

According to documentation of time, it returns the exit code of the command but I also execute an echo command in function. So, anyone has an idea about how can I get exit code of ipython command? Thanks.


Solution

  • Your quoting in your sample call is unusual. I would expect that

    sh -c "ipython -c "%run ./foo.ipynb" > $(log_file "log_file_name") 2>&1"
    

    is translated to

    sh -c 'ipython -c %run' './foo.ipynb > somewhere/logs/log_file_name_somedate.log 2>&1'
    

    As for the behaviour of time wrt return codes, my bash (5.1.16) behaves like this:

    $ time ls "I do not exist" > $(echo newfile) 2>&1
    
    real    0m0,004s
    user    0m0,004s
    sys     0m0,000s
    
    $ echo $?
    2
    
    $ cat newfile
    "I do not exist": No such file or directory (os error 2)
    

    And wrt to redirections like this:

    $ capture="$(time (ls "I do not exist" > $(echo newfile2) 2>&1) 2>&1)"
    
    $ echo $?
    2
    
    $ echo "$capture"
    
    real    0m0,004s
    user    0m0,004s
    sys     0m0,000s
    
    $ cat newfile2
    "I do not exist": No such file or directory (os error 2)
    

    Therefore, I'd suggest you to try changing your call to:

    CODE_TIME="$(time (sh -c "ipython -c '%run ./foo.ipynb' > $(log_file "log_file_name") 2>&1") 2>&1)"
    
    CODE_RESULT=$?