Home > Software engineering >  How to create a file on the command line and pass as an argument to a command
How to create a file on the command line and pass as an argument to a command

Time:08-15

I call a library like this:

$ grun TestLexer tokens -tokens myFile.txt

However, instead of passing a file, I'd like to create/re-create that every time I run it in the command-line such as something like the following:

$ grun TestLexer tokens -tokens "echo 'x 1' > myFile.txt"

What would be the proper way to actually do that?

CodePudding user response:

Bash has process substitution.

You can run a command and make its output available to another command as if it were a file:

$ grun TestLexer tokens -tokens <(echo 'x 1')

To see what is happening, consider:

$ echo <(echo 'x 1')

grun reads from stdin if a filename is not provided, so you could also pass a here-doc / here-string, or pipe in the data:

$ grun TestLexer tokens -tokens <<<'x 1'
$ echo 'x 1' | grun TestLexer tokens -tokens

CodePudding user response:

Would this be an option?

echo 'x 1' > myFile.txt && grun TestLexer tokens -tokens myFile.txt

or perhaps in the case that this can be run multiple times concurrently (in case myFile.txt would be overwritten) or you dont want to commit to a filename:

tmp=$(mktemp) && echo 'x 1' > $tmp && grun TestLexer tokens -tokens $tmp  && rm -f $tmp
  • Related