2

I have a BASH script called script.sh that takes 3 arguments and runs an executable file with them. The first two are just numbers, but the last is an argument giving the input file. I would like the script to run the executable with the input as an argument of the executable and using the "<" as a replacement for stdin. (i.e.

bash script.sh 5 1 input.txt

calls the BASH script, and the contents of script.sh are as follows:

#!/bin/bash

command1="./l${1}t${2} $3"
command2="./l${1}t${2} < $3"

echo + ${command1}
${command1}

echo + ${command2}
${command2}

When I echo command1 I get

./l5t1 input.txt

which is exactly what I want and it runs just fine.

When I echo command2 I get

./l5t1 < input.txt

which is again what I want. The problem is the actual command the script runs is

./l5t1 '<' input.txt

which of course causes a segmentation fault in my program.

I'd like to know if there is a way I can run command 2 so that it runs the string exactly as it is printed in the echo output. Honestly, I have no idea why the single quotes are even inserted around the < character.

1
  • 1
    Anyways, you should be able to eval the contents of the variable. Commented Oct 2, 2013 at 18:56

1 Answer 1

4

If you want to store commands it's better to use functions than variables. As you've found out, redirections don't work when stored in variables (nor do |, ;, or &).

command1() {
    "./l${1}t${2}" "$3"
}

command2() {
    "./l${1}t${2}" < "$3"
}

command1 "$@"
command2 "$@"

Here I've defined two functions, which are called with the arguments from the array $@. "$@" forwards the script's arguments to the functions.

Notice also that I've put quotes around "./${1}t${2}" and "$3". Using double quotes allows these parameters to contain spaces. Liberal quoting is a good defensive scripting technique.

(I strongly recommend not doing eval "$command2". Using eval is a really dangerous habit to get into.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.