Remove Command-Line Option from String

I want to add a "-r <remote_host>" option to my ksh script, causing the script to run a script of the same name on the specified remote host. The remote invocation should itself include all the command-line options of the original invocation, less the -r option.

For example, this invocation:

# the_script -a -b -r the_remote_host -x x_option_value -y arg1 arg2

would execute this:

ssh the_remote_host the_script -a -b -x x_option_value -y arg1 arg2

My problem is removing the "-r <remote_host>" text from $* when bulding the remote invocation. I've tried sed, but I'm not getting it.

C:\cygwin\tmp>echo the_script -a -b -r the_remote_host -x x_option_value -y arg1 arg2 | sed 's/-/~-/g' | tr "~" "\n" | egrep -v "\-r" | tr -d "\n"
the_script -a -b -x x_option_value -y arg1 arg2
C:\cygwin\tmp>

Note, interesting that:

C:\cygwin\tmp>echo the_script -a -b -r the_remote_host -x x_option_value -y arg1 arg2 | sed 's/-/~-/g' | tr "~" "\n"
the_script
-a
-b
-r the_remote_host
-x x_option_value
-y arg1 arg2

breaks your script out so each option is on its own line. perhaps useful?

That doesn't work for me:

$ echo the_script -a -b -r the_remote_host -x x_option_value -y arg1 arg2 | sed 's/-/~-/g' | tr "~" "\n" | egrep -v "\-" | tr -d "\n"
the_script $ 

I can't see how you got the output you did from that command. Where's the logic to check for "-r ..." and remove that part of the string?

cat the_script
ssh ${@:4:1} ${@:1:2} ${@:5}

and you call it exactly like this

./the_script -a -b -r the_remote_host -x x_option_value -y arg1 arg2

Matt,
try my previous post now... was missing a character somehow
should have been:

C:\cygwin\tmp>echo the_script -a -b -r the_remote_host -x x_option_value -y arg1 arg2 | sed 's/-/~-/g' | tr "~" "\n" | egrep -v "\-r" | tr -d "\n"
the_script -a -b -x x_option_value -y arg1 arg2
C:\cygwin\tmp>

And this won't care the order of your switches.

That looks like it's designed exclusively for the example I posted, but I'm looking for a more generic solution. The "-r <remote_host>" text might be anywhere in $@.

---------- Post updated at 09:03 PM ---------- Previous update was at 08:55 PM ----------

That works for the example I posted, but it seems to assume that the text I need to remove is bounded by minus signs. For example, if "-r ..." is the last option, and is followed by arguments, that code doesn't pass the arguments through:

# echo the_script -a -b -r the_remote_host arg1 arg2 | sed 's/-/~-/g' | tr "~" "\n" | egrep -v "\-r" | tr -d "\n"                     
the_script -a -b

The approach of splitting into multiple lines and using "grep -v" is interesting, though.

options=$(sed 's/\(.*\) *-r [^ ]*\(.*\)/\1\2/' <<<"$@")
remHost=$(sed 's/.* *-r \([^ ]*\).*/\1/' <<<"$@")
ssh $remHost $options
1 Like

That's what I needed. Thanks.