help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: i dont see my code error there ...


From: Greg Wooledge
Subject: Re: i dont see my code error there ...
Date: Thu, 31 Mar 2022 15:42:05 -0400

On Thu, Mar 31, 2022 at 08:25:15PM +0200, Alex fxmbsw7 Ratchev wrote:
> <xmb> # t() { TIMEFORMAT=%Rs time { &>/dev/null eval "$@" ; } ; }

Bash's 'time' command isn't a regular command.  It's a keyword.  It has
special rules, and is magical.

When you do "FOO=bar time", you force bash to use a regular command
instead of the magical keyword.  Because "FOO=bar cmd" is only permitted
for regular commands.  It's part of the "simple command" syntax.

unicorn:~$ t() { TIMEFORMAT=%Rs time eval "$*"; }
unicorn:~$ t sleep 1
time: cannot run eval: No such file or directory
Command exited with non-zero status 127
0.00user 0.00system 0:00.00elapsed 81%CPU (0avgtext+0avgdata 1096maxresident)k
0inputs+0outputs (0major+40minor)pagefaults 0swaps

"time: cannot run eval:" comes from the /usr/bin/time command in the
file system, not from the bash keyword.

Also, using "$@" here doesn't make any sense.  You want to pass the
command string along to eval untouched, so use "$*" instead.

This will work:

unicorn:~$ t() { local TIMEFORMAT=%Rs; time eval "$*"; }
unicorn:~$ t sleep 1
1.002s
unicorn:~$ t 'if false; then echo nonsense; else echo ok; fi'
ok
0.000s

Or, with the redirections:

unicorn:~$ t() { local TIMEFORMAT=%Rs; time eval "$*" >/dev/null 2>&1; }
unicorn:~$ t 'if false; then echo nonsense; else echo ok; fi'
0.000s

In fact, if the whole purpose of this exercise is to add the redirections
when you're using time, maybe what you really want is a magic alias.

unicorn:~$ t_helper() { local TIMEFORMAT=%Rs cmd; read -r _ _ cmd < <(history 
1); time eval "$cmd" >/dev/null 2>&1; }
unicorn:~$ alias t='t_helper # '
unicorn:~$ t if sleep 1; then echo zzzz; fi
1.002s

You're a big alias fan, so that should be right up your alley.  It lets
you skip adding the quotes around the "argument" of t, because it's not
really an argument at that point.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]