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.
2 Answers
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 fooThe function
eprints 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
- function Man Page - Linux - SS64.com
- A bash function that takes argument like other languages? - Unix & Linux Stack Exchange
- Passing parameters to a Bash function - Stack Overflow
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)