build command by concatenating string in bash
- by Lennart Rolland
I have a bash script that builds a command-line in a string based on some parameters before executing it in one go. The parts that are concatenated to the command string are supposed to be separated by pipes to facilitate a "streaming" of data through each component.
A very simplified example:
#!/bin/bash
part1=gzip -c
part2=some_other_command
cmd="cat infile"
if [ ! "$part1" = "" ]
then
cmd+=" | $part1"
fi
if [ ! "$part2" = "" ]
then
cmd+=" | $part2"
fi
cmd+="> outfile"
#show command. It looks ok
echo $cmd
#run the command. fails with pipes
$cmd
For some reason the pipes don't seem to work. When I run this script i get different error messages relating usually to the first part of the command (before the first pipe).
So my question is whether or not it is possible to build a command in this way, and what is the best way to do it?