0

I have a string that might be:

  • user:pass@host // case #1
  • user@host // case #2
  • host // case #3

(It's a mongoDB connection string, if you're curious)

I need to end up with:

Case #1: user:pass@host

  • $hostVar -> host
  • $userVar -> user
  • $passVar -> pass

And then run:

mongodump --host $host -u $user -p $pass ...

Case #2: user@host

  • $hostVar -> host
  • $userVar -> user
  • $passVar -> (empty)

And then run:

mongodump --host $host -u $user ...

Note: the -p parameter to mongo is not passed.

Case #3: host

  • $hostVar -> host
  • $userVar -> (empty)
  • $hostVar -> (empty)

And then run:

mongodump --host $host ...

Note that -u and -p are not passed.

So...

I am going insane because of the optional nature of the parameters. My first solution was a classic:

user=$(echo $DBHOST | cut -d : -f 1)
pass=$(echo $DBHOST | cut -d : -f 2 | cut -d @ -f 1)
host=$(echo $DBHOST | cut -d : -f 2 | cut -d @ -f 2)

However, if bits are missing, this completely breaks down.

I tried conditional parsing, based on the presence of :, but the result was... well, embarrassing to show here.

The second issue is then: is there a way to "maybe" pass parameters to a command without conditionals? Something like hostParam="--host $host" and then passing $hostParam would work?

ALL of this is because mongodump doesn't support mongo's connection string, and I have a setting variable in the format I showed in the config file...

Merc
  • 16,277
  • 18
  • 79
  • 122

1 Answers1

1

I would do:

# $conn holds the connection string

# this array will contain the parameters
params=()

if [[ $conn =~ ^(.+):(.+)@(.+)$ ]]; then
    params=( -u "${BASH_REMATCH[1]}" -p "${BASH_REMATCH[2]}" --host "${BASH_REMATCH[3]}" )
elif [[ $conn =~ ^(.+)@(.+)$ ]]; then
    params=( -u "${BASH_REMATCH[1]}" --host "${BASH_REMATCH[2]}" )
else
    params=( --host "$conn" )
fi

# call the command
mongodump "${params[@]}"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Jesus bash has evolved since my time... would you be able to tell me what that `params[@]` is...? The `BASH_REMATCH` is magic, I love it! – Merc Dec 20 '17 at 03:28
  • I know it says "don't just thank you", but... really, seriously thanks. Amazing, concise, to the point and gorgeous coding. – Merc Dec 20 '17 at 03:56
  • `"${params[@]}"` refers to the elements of the array `params` as a list of quoted arguments (similarly to how `"$@"` are the positional parameters with any quoting etc intact). – tripleee Dec 20 '17 at 07:52
  • [This question](https://stackoverflow.com/q/12314451/7552) and its answers details the differences between `"$@"` and `"$*"` and `$@` and `$*`, and the same conclusions can be reached about accessing the elements of an array `"${params[@]}"` vs `"${params[*]}"` vs `${params[@]}` vs `${params[*]}` – glenn jackman Dec 20 '17 at 14:21