4

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?

  • 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 Aug 14 '14 at 16:12
6

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
}
|improve this answer|||||
  • 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 Aug 14 '14 at 18:41

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.