Pedro Gordo
Pedro Gordo

Reputation: 1865

How to pass all arguments to a script called by /bin/bash

I have a script that I want it to receive a number of variable arguments and pass them to the execution of another script, but I'm only being able to pass the first argument set by the first call.

My script (nodetool_improved) looks like this:

sudo su cassandra -s /bin/bash -c "/usr/local/cassandra/bin/nodetool -u cassandra -pwf /opt/apps/cassandra/resources/security/jmxremote.password $@"

If I call it like:

$ nodetool_improved status

Then /usr/local/cassandra/bin/nodetool receives status, and the output looks OK. But if I call my script like:

$ nodetool_improved help status

Then the output instead of showing the help for the status option, just shows the help for all options, which is effectively the same as calling:

$ /usr/local/cassandra/bin/nodetool help

That means that help status is not being passed to /usr/local/cassandra/bin/nodetool. Only help.

How can I change my nodetool_improved script so that all arguments are passed to /usr/local/cassandra/bin/nodetool?

Some things I've tried and which don't work:


sudo su cassandra -s /bin/bash -c "/usr/local/cassandra/bin/nodetool -u cassandra -pwf /opt/apps/cassandra/resources/security/jmxremote.password -- '$@'"

Error:

status': -c: line 0: unexpected EOF while looking for matching `''
status': -c: line 1: syntax error: unexpected end of file

sudo su cassandra -s /bin/bash -c '/usr/local/cassandra/bin/nodetool -u cassandra -pwf /opt/apps/cassandra/resources/security/jmxremote.password "$@"' -- "$@"

Error:

Only the status gets picked up. The output is the same as if I called it like:

/usr/local/cassandra/bin/nodetool status

Upvotes: 0

Views: 172

Answers (2)

tripleee
tripleee

Reputation: 189908

You can't use '$@' inside double quotes to get the same semantics as "$@". Instead I would pass the arguments outside of the quoted string.

sudo su cassandra -s /bin/bash -c '/usr/local/cassandra/bin/nodetool -u cassandra -pwf /opt/apps/cassandra/resources/security/jmxremote.password "$@"' _ "$@"

Inside the single quotes you have the literal string "$@" which then gets populated by Bash with the arguments to bash -c '...' which come after the string. (The -- is required because the first token after bash -c '...' is used to populate $0, not $@.)

Upvotes: 2

RKou
RKou

Reputation: 5231

You need to use "--" to stop the parameter interpretation (it works if nodetool accepts this using getopt). So, try:

sudo su cassandra -s /bin/bash -c "/usr/local/cassandra/bin/nodetool -u cassandra -pwf /opt/apps/cassandra/resources/security/jmxremote.password -- '$@'"

Upvotes: 0

Related Questions