8

I'm trying to source a file whose name is passed from stdin. My plan is to create a function like this:

mySource() {
    # get stdin and pass it as an argument to `source`
    source $(cat)
}

to be called like this: $ echo "file1.sh" | mySource wherein file1.sh is:

FILE=success
export FILE

Assuming $FILE is initialized to hello world, when I run $ echo "file1.sh" | mySource, I expect $ echo $FILE to print success; however, instead it prints hello world.

Is there some way to source a file from a function?

1
  • You can first replace your source $(cat) with read file; source $file. That's the usual way to read a word from standard input.
    – lgeorget
    Commented Aug 14, 2014 at 16:12

1 Answer 1

9

You can change your mySource function to:

mySource() {
  source "$1"
}

Then calling it with:

$ mySource file.sh
$ printf '%s\n' "$FILE"
success

You can also make mySource handles multiple files:

mySource() {
  for f do
    source "$f"
  done
}
2
  • 1
    Boom. That's the answer. Extra kudos for predicting the multi-file use case which I was actually trying to support. For posterity's sake, you might want to remove from the source code snippets the comment about "getting from stdin" since we're no longer doing that.
    – weberc2
    Commented Aug 14, 2014 at 18:41
  • @cuonglm so is totally valid do a source within a method? Commented Feb 17, 2022 at 13:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .