Girrafish
Girrafish

Reputation: 2482

Delete final positional argument from command in bash

I have a script called dosmt where I input a couple args and then print something:

if [ "${@: -1}" == "--ut" ]; then
    echo "Hi"
fi

What I'm trying to do is delete the last positional argument which is --ut if the statement is true. So if my input were to be $ dosmt hello there --ut, it would echo Hi, but if I were to print the args after, I just want to have hello there. So basically I'm trying to delete the last argument for good and I tried using shift but that's only temporary so that doesn't work...

Upvotes: 5

Views: 1009

Answers (1)

John1024
John1024

Reputation: 113834

First, let's set the parameters that you want:

$ set -- hello there --ut

We can verify that the parameters are correct:

$ echo "$@"
hello there --ut

Now, let's remove the last value:

$ set -- "${@: 1: $#-1}"

We can verify that the last value was successfully removed:

$ echo "$@"
hello there

Demonstration in a script

To demonstrate this as part of a script:

$ cat script
#!/bin/bash
echo Initial values="$@"
set -- "${@: 1: $#-1}"
echo Final values="$@"

We can run with your arguments:

$ script hello there --ut
Initial values=hello there --ut
Final values=hello there

Upvotes: 8

Related Questions