3

I'd like to create a bash function that can get a bash code block like time does:

time {
  echo 123
  echo "Something else"
  sleep 1
}

Basically I'd like to be able to wrap the block with my bash code.

Edit: Updated my question after the first answer of @DavidPostill♦ and the comments: For example, I'd like to wrap a code block with 2>&1 > /dev/null and also the time it with time. Should I write a program outside bash to do that?

function myfunction() {
  time { $1 } 2>&1 /dev/null
}
myfunction { sleep 1 }

Edit 2: Upon further reading it seems like it isn't possible as time is a special case for bash.

funerr
  • 177
  • 1
  • 1
  • 6
  • 2
    Note: `time` can do this because its a *keyword* in Bash. It's recognized by the parser. If you use `/usr/bin/time` instead (or `command time` or some function or a builtin), then it will be a syntax error. What exactly do you want your function to do? Maybe we can do this using a different syntax. – Kamil Maciorowski Oct 04 '20 at 12:56
  • 1
    Can't do this in bash. The closest you get is to define a function containing the code you want as a block, and then pass the function name to your function that wants a block. – glenn jackman Oct 04 '20 at 14:14
  • I'd like to wrap a code block with 2>&1 > /dev/null and also time it with `time`. Should I write a program outside bash to do that? – funerr Oct 04 '20 at 18:24
  • 2
    Somewhat similar: [Wrapping `time` (and similar keywords) in call from another script](https://superuser.com/q/904339/432690). – Kamil Maciorowski Oct 04 '20 at 18:31
  • So, it seems it isn't possible with the syntax I had in mind, right? what are my options, per the edit? – funerr Oct 04 '20 at 22:58

2 Answers2

0

I'd like to be able to wrap the function with my bash code and pass arguments

Functions with parameters sample

#!/bin/bash 
function quit {
   exit
}  
function e {
    echo $1 
}  
e Hello
e World
quit
echo foo 

The function e prints the first argument it receives.

Arguments, within functions, are treated in the same manner as arguments given to the script.

Source BASH Programming - Introduction HOW-TO: Functions


Further reading

DavidPostill
  • 153,128
  • 77
  • 353
  • 394
0

You can't pass blocks around directly as if they were objects, but you can pass the file descriptor (FD) of a redirect block (<()) and time the output of that (or do whatever to it). The inner {} 2>&1 is needed to capture the stderr on the same FD:

function myfunction() {
  time cat $1 >/dev/null
}
myfunction <({ 
  echo 123
  echo "Something else"
  sleep 1 
} 2>&1)
Droj
  • 619
  • 7
  • 5