Bash – source /dev/stdin doesn’t work as expected

bashpipeshell-script

Let's start with simple tests that work for me to check that source /dev/stdin can be used at all.

# echo -ne 'echo a\necho b\n' | source /dev/stdin
a
b

Now I would like to source an actual function.

# echo -ne 'f() { echo a; }\n' | source /dev/stdin
# f
-bash: f: command not found

Now let's try with a temporary file.

# echo -ne 'f() { echo a; }\n' > tempf
# source tempf
# f
a

So the temporary file works. But it's very incovenient in my case and I don't see any valid reason why the pipe shouldn't work just as well.

# bash --version
GNU bash, version 4.2.53(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

For completeness, the actual use case is to carfully select which parts of a file will be included, in order to work around over a limitation in Gentoo portage.

post_src_unpack() {
    if type epatch_user > /dev/null 2>&1; then
        epatch_user || die
    else
        awk \
            '/^# @FUNCTION: / { p = 0 } /^# @FUNCTION: epatch(_user)?$/ { p = 1; } p { print  }' \
            /usr/portage/eclass/eutils.eclass | source /dev/stdin || die
        epatch_user || die
        unset epatch
        unset epatch_user
    fi
}

The purpose of the code is to extract just two required functions epatch and epatch_user from a source file with lots of functions, make them available in the current shell, run one of them (which in turn uses the other), and remove them. The final goal is to workaround the limitation of Gentoo that only ebuilds inheriting eutils have access to epatch_user.

Best Answer

You can use process substitution

source /dev/stdin < <(echo -ne 'f() { echo a; }\n')

or

source <(echo -ne 'f() { echo a; }\n')

This works in bash 4.1.5, for some reason it doesn't work in 3.2.48.

Related Question