Pierre
Pierre

Reputation: 3

How can I pass through all but one (not first/last) command line argument, w/o losing quoting?

I have a script called as:

myscript "first argument" "second argument" "third argument" ...

I want to call a function from that script as:

anotherFunction "first argument" "third argument" ...

I'm trying to transform $@ using echo, but the quoting keeps getting lost. My current attempt looks like the following, but it doesn't work; anotherFunction gets called with the wrong arguments.

delete() {
    commandLine=`echo "$commandLine" | sed "s|$1||"`
}
anotherFunction() {
    echo "Called with first argument:  $1"
    echo "Called with second argument: $2"
}

# shown as a function here so it can be copied and pasted to test
# works the same way when it's actually an external script
myscript() {
  commandLine="$@"
  delete $2
  anotherFunction $commandLine
}

myscript "first argument" "second argument" "third argument"

The output I want this to have is:

Called with first argument:  first argument
Called with second argument: third argument

...but instead it's emitting:

Called with first argument:  first
Called with second argument: argument

Upvotes: 0

Views: 70

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295619

If your goal is to make myScript "foo" "bar" "hello world" run anotherFunction "foo" "hello world" -- deleting the second argument -- that would look like the following:

args=( "$1" "${@:3}" )
anotherFunction "${args[@]}"

You could also write it as:

args=( "$@" )
unset args[1]
anotherFunction "${args[@]}"

Upvotes: 2

Related Questions