Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a Bash variable in place of a file as input for an executable

Tags:

file

bash

pipe

I have an executable that is used in a way such as the following:

executable -v -i inputFile.txt -o outputFile.eps

In order to be more efficient, I want to use a Bash variable in place of the input file. So, I want to do something like the following:

executable -v -i ["${inputData}"] -o outputFile.eps

Here, the square brackets represent some clever code.

Do you know of some trick that would allow me to pipe information into the described executable in this way?

Many thanks for your assistance

like image 603
d3pd Avatar asked Feb 12 '13 19:02

d3pd


People also ask

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

Which command is used in bash to set a variable from user input?

Ask the User for Input. If we would like to ask the user for input then we use a command called read. This command takes the input and will save it into a variable.


3 Answers

You can use the following construct:

<(command) 

So, to have bash create a FIFO with the command as the output for you, instead of your attempted -i ["${inputData}"], you would do:

-i <(echo "$inputData") 

Therefore, here is your final total command:

executable -v -i <(echo "$inputData") -o outputFile.eps 
like image 150
mikyra Avatar answered Sep 27 '22 20:09

mikyra


Echo is not safe to use for arbitrary input.

To correctly handle pathological cases like inputdata='\ntest' or inputdata='-e', you need

executable -v -i <(cat <<< "$inputData")

In zsh, the cat is not necessary


Edit: even this adds a trailing newline. To output the exact variable contents byte-by-byte, you need

executable -v -i <(printf "%s" "$inputData")
like image 38
Eric Avatar answered Sep 27 '22 20:09

Eric


Note: zsh only:

To get a filename containing the contents of ${variable}, use:

<(<<<${variable})

Note:

  • <<<${variable} redirects STDIN to come from ${variable}
  • <<<${variable} is equivalent to (but faster than) cat <<<${variable}

So for the OP's case:

executable -v -i <(<<<${inputData}) -o outputFile.eps
like image 41
Tom Hale Avatar answered Sep 27 '22 19:09

Tom Hale