When you are creating tutorials online for people to use in a single terminal sometimes it's nice to source inline code...however none of these worked as I would expect. I would expect foo to be "bar" for all of these. Anyone know why?

#!/usr/bin/env bash

source <(echo "export foo=bar");
echo "$foo"

source <(cat <<< "export foo=bar");
echo "$foo"

source <(cat <<EOF
  export foo=bar


echo "$foo"

My only guess is that source cannot read from a file descriptor? I also tried using . instead of source same thing.

I am on MacOS, bash --version output:

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18) 
Copyright (C) 2007 Free Software Foundation, Inc.
  • 1
    These all work in bash release 5.0.7(1). You should probably mention what actually happens when you run this, as well as what your bash version is. – Kusalananda May 30 '19 at 17:04
  • Show your actual output. Also show your bash version: echo "$BASH_VERSION" – glenn jackman May 30 '19 at 17:14
  • Why can't you just use eval? Yes, you can work around that bug with source /dev/fd/0 <<<'export foo=bar' (which will use a regular/seekable tempfile), but it's just as completely pointless as your examples. – mosvy May 30 '19 at 17:59
  • Yeah eval might work - it's for copying commands to current terminal – Alexander Mills May 30 '19 at 18:01

This would not work in bash releases before release 4.0 (for example, the default bash on macOS, which is release 3.2.57(1)).

Release 4.0 had a bugfix:

Fixed a bug that caused `.' to fail to read and execute commands from non- regular files such as devices or named pipes.

(that's from https://tiswww.case.edu/php/chet/bash/CHANGES)

The file read by source (or .) when you use it with a process substitution is not a regular file, so it would trigger the bug that was fixed in release 4.0.

The most recent release is currently release 5.0.7(1), where your code works as expected.

  • 1
    @Alexander, if you are on a mac, install bash via homebrew to get a more recent version. – glenn jackman May 30 '19 at 17:17
  • Anybody know of a good way to easily switch between bash versions 3 4 and 5 on a machine? – Alexander Mills May 30 '19 at 17:21
  • 1
    @AlexanderMills Clone the Git repository (git://git.savannah.gnu.org/bash.git) and check out the appropriate tag and build it? – Kusalananda May 30 '19 at 18:56
  • thanks I used the technique here to build from gnu bash source: unix.stackexchange.com/questions/522023/… – Alexander Mills May 30 '19 at 19:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.