# selectively remove arguments from shell script



## tOsYZYny (May 20, 2022)

I have been writing a bunch of shell scripts that essentially wrap existing commands so I don't need to remember the intricate details for most of what I want to do.

I have a shell script that essentially builds parameters to call another executable.  Some of the arguments should not be changed, but there are some that are used just by the shell script itself to determine which downstream executable to call or how it should be called.

If I have this:


```
wrapper --delete arg1 arg2
wrapper  arg1 arg2 --delete
```

I supposed I could always require the arguments to be properly ordered so that a simple call to shift will work, but if I don't want to require that, is there anyway I can remove the '--delete' argument altogether?


----------



## mer (May 20, 2022)

Depending on what shell (bash, sh, Perl, etc) there are probably a few different ways.
The easiest would be something like:
loop through argv
  if argv[n] should be kept, store at dupargv[k] k++ else dosomethingdifferent
  n++
end loop
call otherscript with dupargv

If the script is in something like Perl or even bash there may be ways to read the whole argv[] as a single
string and do things like sed or awk on it.


----------



## tOsYZYny (May 20, 2022)

I am using /bin/sh to keep my shell scripts simple.


----------



## mer (May 20, 2022)

I think looping through the input argv[] then is likely a way of doing it.
Is the "--delete" an argument that determines the downstream executable?
If so I think there is a "getopts" that can help.  I'm going by memory so can't give concrete examples.  I think it's available in sh.  Using it you should be able to quickly parse and separate things.


----------



## tOsYZYny (May 20, 2022)

I will check more if getopts is available in sh, I know it is for bash.


----------



## covacat (May 20, 2022)

```
#!/bin/sh
echo $*
set -- $(echo $*| sed -e  "s/--delete//")
echo $*
```


```
~$sh  b.sh a b --delete
a b --delete
a b
~$sh  b.sh --delete a b
--delete a b
a b
```


----------



## tOsYZYny (May 20, 2022)

That is genius, that worked!


----------

