I want the output of the time command to be shown only if the command, which has been passed to time was successful. Something like this:

( time wget -pq --delete-after https://www.example.com ) 2>&1 || echo fail

The problem is, that if wget fails, I still receive the output from time (which is somewhere logical, as it measures how long it took for the command to fail anyway). My goal is to save the output to a variable and either have 0m0.100s or fail in my variable. Does anyone has an idea how I could do this in a decent manner?


You can do something like this:

$ if var=$( { time true; } 2>&1 ); then echo "$var"; else echo fail; fi

real    0m0.000s
user    0m0.000s
sys 0m0.000s

$ if var=$( { time false; } 2>&1 ); then echo "$var"; else echo fail; fi
  • 2
    var=$( { time sleep 1; } 2>&1 ) should work with Bash, ksh and zsh (though time true doesn't print anything in my zsh, hmm) – ilkkachu Feb 8 at 16:05
  • @ilkkachu Brief look through zsh docs seems to suggest there's times but no time, though there is an extension for that apparently. Maybe /bin/time is better choice if portability is a concern ? – Sergiy Kolodyazhnyy Feb 28 at 3:48
  • @SergiyKolodyazhnyy, type time says time is a reserved word on my zsh. But doing time foo where foo is a builtin doesn't print anything from time... time true is silent, but time /bin/true prints the (near-zero) time it took to run /bin/true. – ilkkachu Feb 28 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.