linuxbashshellvariablesroot-framework

Is there something similar to #define in C/C++ for a bash script?


I am currently working on a script which calls a few programs, e.g.:

root -l -q Analysis.C+'("var1", "var2", "var3")'

I now want a bash script that automatically replaces the user input with var1, var2, var3, etc. However, if I write something like

root -l -q Analysis.C+'("$1", "$2", "$3")'

this does not seem to work, as it intrprets $1 and so an as strings and not as variables. Is there something similar to #define like in C/C++ where the variable is replaced in the whole script before running? Or how can this be done?


Solution

  • No, you cannot perform preprocessing regardless of quoting context. This is because the very point of quoting contexts in shell is to control which kind of substitutions do and don't take place. If you could define substitutions that happened in single quotes, the meaning that single-quotes have in shell (that characters within them as treated as literal and not subject to expansions) would be lost.


    Doing this right would look something like:

    root -l -q Analysis.C+'("'"$var1"'", "'"$var2"'", "'"$var3"'");'
    

    That is to say: The single-quoted context is ended, and a double-quoted context is started, before each parameter substitution.


    The effect of this can be seen below:

    $ var1=a; var2=b; var3=c
    $ printf '%s\n' root -l -q Analysis.C+'("'"$var1"'", "'"$var2"'", "'"$var3"'");'
    root
    -l
    -q
    Analysis.C+("a", "b", "c");