chell
chell

Reputation: 117

Append a command in a Bash script using a colon and an optional positional parameter?

I have a small Bash script that runs a command that is essentially one long string containing environment variables, ending in a path to a file.

function ios-run-test() {
  thing="DEVICE_TARGET=abcde12345
  DEVICE_ENDPOINT=http://192.168.1.1:37265
  BUNDLE_ID='com.app.iPhoneEnterprise'
  DISABLE_ADS=1
  env=$1
  DISABLE_LOGIN_INTERSTITIALS=1
  bundle exec cucumber --tags ~@wip --tags ~@ignore --tags ~@android
  ~/Automation/ios-automation/features/$2.feature"

  if [[ $3 ]]; then
    add_this=$3
    thing="${thing:$add_this}"
  fi

  echo ${thing}
  eval universal-variables
  eval ${thing}

}

Sometimes that command may end with a :some_integer, such as DEVICE_TARGET=abcde12345 DEVICE_ENDPOINT=http://192.168.1.1:37265 BUNDLE_ID='com.app.iPhoneEnterprise' DISABLE_ADS=1 env=production DISABLE_LOGIN_INTERSTITIALS=1 bundle exec cucumber --tags ~@wip --tags ~@ignore --tags ~@android ~/Automation/ios-automation/features/login.feature:5. This is where my problem lies. I have discovered Substring Extraction which is pretty neat, but is causing this if statement to fail:

  if [[ $3 ]]; then
    add_this=$3
    thing="${thing:$add_this}"
  fi

Instead of appending $thing to have ":$3" it is removing the first 3 characters of $thing. Is there some other way that I'd be able to take an optional positional parameter and append it to the command?

Upvotes: 0

Views: 1029

Answers (1)

janos
janos

Reputation: 124744

If you just want to append :$3, then change this line:

thing="${thing:$add_this}"

To this:

thing="${thing}:$add_this"

Appending values in Bash works by simply writing them one after the other. The braces are optional in this example, so simply thing="$thing:$add_this" is equivalent. Inside ${...} you can perform various advanced operations based on a variable, but none of that is necessary or relevant for your use case.

Upvotes: 2

Related Questions