I am trying to write a script that takes in 2 parameters - program name and optional flags.

I am trying to execute the program command on an input_file and store the output in the output_file.

$input_file < $($program options) > output_file

I have tried various combinations of syntax to achieve the above behaviour but I am getting errors such as: ambiguous redirect,i/o error, etc.


./execute cat -n 

Inside the program I want to write code such that cat is applied on input file

these didn't work:

$(${1} ${2} names.txt) > test.out
names.txt < $($1 $2) > test.out

You misunderstand the syntax. First, input redirection has the < symbol in front of the file, not at the back. The order of operations is not important. So, the syntax is:

< inputfile command options > outputfile


command options < inputfile > outputfile

(or other permutations).

Then, you also have extra $. What you really need to do is

$program $options <$inputfile >$outputfile

You can replace ${program} and ${options} with $1 and $2.

In this form, you can do

<names.txt $1 $2 >test.out

And call it as ./execute cat -n or even ./execute cat '-n -s' if you want more than one option. In this form, you can have multiple options, but you have to put them into quotes (because $2) isn't quoted, the spaces expand the parameter back into multiple words.

Another (better) way of doing it would just be to use

<names.txt "$@" >test.out

Now, you can pass an arbitrary number of parameters into the script, and you can even have quoted strings in the arguments and they stay together after propagation into the script. Now this works: ./execute cat -n - "bla bla.txt" (the previous form would split the filename into two parts).


This is one possible solution:

concatenate the command and options string so that we don't have to deal with lot of parentheses.

command="$1 $2"
$command input_file > output_file

(Please let me know if I am overlooking something)

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.