Search code examples
bashscriptingdouble-quotes

Executing a command (read from an external file) containing Double quoted parameters


Let's say I have a file.txt file like this:

some words
from here
blah blah blah
that begins
this is this

to here
other content

and another file called *config.conf" like this:

name1:value1
name2:value2    
expr:sed -re "s/this/that/g" -ne "/from here/,/to here/ p"
name3:value3
name4:value4

In my script.sh I need to get the whole sed command that is written after "expr:" in the config.conf and execute it in a pipe like this :

#!/bin/bash

pipecommand=$(cat info | grep -e "^expr:" | sed -re "s/^expr://g")
cat file.txt | $pipecommand > output.file

but I get this error:

sed: -e expression #1, char 1: unknown command: `"' 

I've read about many similar questions here and the solution was using an array like this:

pipecommand=($(cat info | grep -e "^expr:" | sed -re "s/^expr://g"))
cat file.txt | ${pipecommand[@]} > output.file

Unfortunately this works only with less complex commands and only if I assign the "sed...blah blah blah" command directly to the variable, without reading it from a file.

Do some of you know a working solution to this?

P.S.: I can change both the script.sh and the config.conf files.


Solution

  • Turn your config file into a plugin with a well-defined interface. Here, your script expects a function named sed_wrapper, so you provide a definition with that name in your "config file" (renamed to lib.sh here).

    # This is lib.sh
    sed_wrapper () {
        sed -re "s/this/that/g" -ne "/from here/,/to here/ p"
    }
    

    Then, in your script, call the named function.

    . lib.sh
    
    sed_wrapper < file.txt > output.file