0

I have a script whose first parameter is an identifier for an object to which every subsequent parameter will be compared.

I know how to use $1, $2, etc. to refer to individual parameters, but how can I store the value of the first and then loop over everything but the first?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Kev Luxem
  • 55
  • 6
  • No matter what else your script contains, the shebang MUST be the first line in the script to be effective. – Mad Physicist Aug 30 '17 at 17:15
  • Thanks for the hint, of course it has to be. I accidentally put it into the code line. – Kev Luxem Aug 30 '17 at 17:21
  • 1
    Eh? `exec` is a builtin that replaces the shell with the command being run. Nothing after it will ever be run in the same shell if it succeeds (since that shell will no longer be in memory). – Charles Duffy Aug 30 '17 at 17:22

1 Answers1

2

The answer to this is a simple extension to Iterate through parameters skipping the first (the only difference being the need to store the first argument before discarding it).

Use shift to pop an argument off the list so you can iterate over the rest. Thus:

#!/usr/bin/env bash
first=$1; shift || exit
for arg; do
  echo "Using first argument $first with additional argument $arg"
done

If you run this script with ./theScript argA argB argC, you'll get the following output:

Using first argument argA with additional argument argB
Using first argument argA with additional argument argC

...which, as best I can tell, is the behavior you're asking for.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441