11

Say I have some configuration data in a file config. For convenience, I'd like to load this data into a shell variable, CONFIG_DATA.

Obviously I can do:

CONFIG_DATA="$(cat config)" 

But this kinda feels like a useless use of cat to me. Is this the only way to do this? Or is there a more elegant way to do it?

Answers should prefer POSIX but may use any shell.

3
  • 2
    Reading an entire file in memory like this is almost always a bad idea, regardless of how you write it. Commented Dec 13, 2016 at 6:36
  • 2
    @SatoKatsura in some cases very true. however for the purpose of this question, you may assume that the file is super tiny, so it's not a major problem. Commented Dec 13, 2016 at 6:42
  • 1
    @SatoKatsura: why? Commented Dec 13, 2016 at 11:20

1 Answer 1

23

In Bash and the Z shell, at least, there is a faster way:

CONFIG_DATA=$(<config) 

To quote from the Bourne Again shell's man page:

The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

2
  • 1
    I'd not consider this a good option. Whatever are OP's feelings towards useless use of cat, the OP's example is simple enough that most Bash users would understand it. It's also quite portable. Now $(<file) is a lot less common, so it might result in much more WTFs; and speed gain from this operation, if such configuration is to be loaded to a variable, is probably negligible Commented Dec 13, 2016 at 12:17
  • 6
    @MatthewRock note that a lot of very bad practices are common and familiar. The useless uses of cat are one example, for i in $(cat file); do ... is another. That they are common is no reason to keep using bad tools. Which is not to say that this particular use of cat is a bad tooi, I'm not sure if there's a more portable way. Just saying that common & familiar != good. Commented Dec 13, 2016 at 12:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.