Glam Prestige Journal

Bright entertainment trends with youth appeal.

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.

5

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 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

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)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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