3

I have a bash script that accepts a parameter "$input" and (among other things) directs it into a program and collects the output.

Currently my line is:

OUTPUT=`./main.exe < $input`

But I get the following error:

$input: ambiguous redirect

What is the correct way to do it?

6

Your variable's value probably contains spaces.

You should double quote it:

output=$( ./main.exe <"$input" )

The bash shell requires that the variable, in this context, is quoted and will otherwise perform word-splitting and filename globbing on its value, while other shell may not require this.

Also, note that $input here is the pathname of a file that will be connected to the standard input stream of your program, not an argument to main.exe (I might have misunderstood your text, but never the less). If you want to use $input as a command line argument instead, your command would look like

output=$( ./main.exe "$input" )

Related:

Also:

  • Shouldn't you add quotes around a $() block in the case the output of the command contains spaces? According to Why does my shell script choke on whitespace or other special characters? it should – Ferrybig Feb 15 at 16:13
  • @Ferrybig: It's not needed when used for variable assignment, the shell will not perform word splitting on it. See Shell Parameters. This is also mentioned in Gilles answer in the linked question When is double-quoting necessary? – Jesse_b Feb 15 at 16:55
  • 2
    @Ferrybig As Jesse said, but it would not hurt to always add them if you're uncertain about where and under what circumstances they are actually needed. – Kusalananda Feb 15 at 17:26
  • Actually the problem disappeared after I replaced the backticks with the $( ... ) syntax. Thanks! – Erel Segal-Halevi Feb 16 at 17:16
  • @ErelSegal-Halevi Just changing the backticks to $( ... ) should not have made a difference. The issue is the quoting of the variable. Using an unquoted variable in < $input should still break horribly if the value in $input contains spaces. – Kusalananda Feb 16 at 17:31

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.