4

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?

1 Answer 1

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:

5
  • 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 Commented Feb 15, 2019 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? Commented Feb 15, 2019 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. Commented Feb 15, 2019 at 17:26
  • Actually the problem disappeared after I replaced the backticks with the $( ... ) syntax. Thanks! Commented Feb 16, 2019 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. Commented Feb 16, 2019 at 17:31

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.