SLY
SLY

Reputation: 535

Append bash parameters and pass forward to other script

I need to pass further original parameters and also I want to add some others. Something like this:

#!/bin/bash
params="-D FOREGROUND"
params+=" -c Include conf/dev.conf"

/usr/local/apache/bin/apachectl $params "$@"

This code above don't work as expected if params contains of two or more parameters, it treated as one parameter.

Upvotes: 2

Views: 110

Answers (2)

steve
steve

Reputation: 1

If the issue is the space in the parameter "-c Include conf/dev.conf" then you could just use a backspace to preserve the space character: params+="-c Include\ conf/dev.conf"

Upvotes: 0

Fred
Fred

Reputation: 6995

The code in your example should work if the following command is valid when executed at the command line written exactly like this :

/usr/local/apache/bin/apachectl -D FOREGROUND -c Include conf/dev.conf "$@"

A quick web search leads me to think that what you want is this (notice the additional double quotes) :

/usr/local/apache/bin/apachectl -D FOREGROUND -c "Include conf/dev.conf" "$@"

Here is how to achieve that simply and reliably with arrays, in a way that sidesteps "quoting inside quotes" issues:

#!/bin/bash
declare -a params=()
params+=(-D FOREGROUND)
params+=(-c "Include conf/dev.conf")

/usr/local/apache/bin/apachectl "${params[@]}" "$@"

The params array contains 4 strings ("-D", "FOREGROUND", "-c" and "Include conf/dev/conf"). The array expansion ("${params[@]}", note that the double quotes are important here) expands them to these 4 strings, as if you had written them with double quotes around them (i.e. without further word splitting).

Using arrays with this kind of expansion is a flexible and reliable to way to build commands and then execute them with a simple expansion.

Upvotes: 4

Related Questions