I have something like this in my bash script:
executor="env UNROLL=${u} TB=${tb} ${APP_DIR}/${tp} ${idx} > output.txt"
$executor
which is not working. I realized that the problem is that it is "escaping" the > character, because if I do:
executor="env UNROLL=${u} TB=${tb} ${APP_DIR}/${tp} ${idx}"
$executor > output.txt
then it is working properly.
How can I fix it to have everything in a single line?
CodePudding user response:
Storing Bash code in variables is a recipe for (un)escaping bugs. Not to mention how dramatically the script’s behavior can change due to (untrusted) values of expanded variables, especially when combined with eval
.
If you want to store a piece of Bash code for later (re)use, use a function:
executor() {
env UNROLL="${u}" TB="${tb}" "${APP_DIR}/${tp}" "${idx}" > output.txt
}
executor
A more flexible option would be to get the expanded variables and the target file name from the executor
function’s arguments, to make it more self-contained and less context-dependent.
executor() {
local -n args="$1"
env UNROLL="${args['UNROLL']}" \
TB="${args['tb']}" \
"${args['APP_DIR']}/${args['tp']}" "${args['idx']}" > "${args['output']}"
}
declare -A some_executor_arguments=(
['UNROLL']='blah_unroll'
['tb']='blah_tb'
['APP_DIR']='/some/dir/blah'
['tp']='some_app'
['idx']='5'
['output']='output.txt'
)
executor some_executor_arguments
CodePudding user response:
I just realized I can do that with eval $executor