Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use stdbuf on a bash function

Tags:

bash

We can use stdbuf on a regular command, e.g.

stdbuf -o 0 echo aaa

However I can't use it on a bash function, e.g.

function tmpf() { echo aaa; }
stdbuf -o 0 tmpf

What's the reason for that? Thanks!

like image 535
Nan Hua Avatar asked Sep 19 '25 18:09

Nan Hua


1 Answers

The reason is that bash functions are internal to the bash session. stdbuf and utilities like that are separate programs with no access to the shell session, and indeed without any knowledge of bash. So it can only run executables.

Because bash has a few tricks up its sleeve, you can export a bash function -- like exporting an environment variable -- which will make the function accessible to bash processes run in children. So you can do this:

function tmpf() { echo aaa; }
export -f tmpf
stdbuf -o 0 bash -c 'tmpf'

but even there, you need to get stdbuf to execute a child bash in order to call the function.

like image 82
rici Avatar answered Sep 22 '25 08:09

rici