简体   繁体   中英

Running variable commands in BASH

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. (ie

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM