How to create a .conf file on the fly in Bash
I have a proprietary command-line program that I want to call in a bash script. It has several options in a .conf file that are not available as command-line switches. I can point the pro开发者_JAVA技巧gram to any .conf file using a switch, -F
.
I would rather not manage a .conf file separate from this script. Is there a way to create a temporary document to use a .conf file?
I tried the following:
echo setting=value|my_prog -F -
But it does not recognize the -
as stdin.
You can try /dev/stdin
instead of -
.
You can also use a here document:
my_prog -F /dev/stdin <<OPTS
opt1 arg1
opt2 arg2
OPTS
Finally, you can let bash allocate a file descriptor for you (if you need stdin for something else, for example):
my_prog -F <(cat <<OPTS
opt1 arg1
opt2 arg2
OPTS
)
When writing this question, I figured it out and thought I would share:
exec 3< <(echo setting=value) my_prog -F /dev/fd/3
It reads the #3 file descriptor and I don't need to manage any permissions or worry about deleting it when I'm done.
You can use process substitution for this:
my_prog -F <(command-that-generates-config)
where command-that-generates-config
can be something like echo setting=value
or a function.
It sounds like you want to do something like this:
#!/bin/bash
MYTMPFILE=/tmp/_myfilesettings.$$
cat <<-! > $MYTMPFILE
somekey=somevalue
someotherkey=somevalue
!
my_prog -F $MYTMPFILE
rm -f $MYTMPFILE
This uses what is known as a "here" document, in that all the contents between the "cat <<-!" up to ! is read in verbatim as stdin. The '-' in that basically tells the shell to remove all leading tabs.
You can use anything as the "To here" marker, e.g., this would work as well:
cat <<-EOF > somewhere
stuff
more stuff
EOF
精彩评论