0
\$\begingroup\$

I have a curl based working bash script, but I have many duplicates on the "CURL" body.

How do I improve it efficiently to eliminate duplications?

if ! npm test
    then
      # Tell the human about the failure, if the npm output wasn't enough
      echo >&2 "Testing failed"
      curl -X POST -H 'Content-type: application/json' --data '{"text":"Tests failed for Platform: '"$PLATFORM"'\nEnvironment: '"$ENVIRONMENT"'"}' https://hooks.slack.com/services/rr/qq/pp

      # Exit and tell computers about the failure (0 = success, 1+ = failure)
      echo "A test Failed" 
      exit 1

    else

      echo "Tests passed" 
      curl -X POST -H 'Content-type: application/json' --data '{"text":"Tests passed for Platform: '"$PLATFORM"'\nEnvironment: '"$ENVIRONMENT"'"}' https://hooks.slack.com/services/rr/qq/pp

    fi
\$\endgroup\$

closed as unclear what you're asking by Toby Speight, 1201ProgramAlarm, IEatBagels, Graipher, Sᴀᴍ Onᴇᴌᴀ Mar 3 at 2:10

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 5
    \$\begingroup\$ Please specify what this code accomplishes, and retitle the question accordingly. See How to Ask. \$\endgroup\$ – 200_success Feb 28 at 6:22
3
\$\begingroup\$

Use a function with a parameter for the variable part to eliminate duplication:

post_report() {
  local result=$1
  curl -X POST -H 'Content-type: application/json' \
      --data '{"text":"Tests '"$result"' for Platform: '"$PLATFORM"'\nEnvironment: '"$ENVIRONMENT"'"}' \
      https://hooks.slack.com/services/rr/qq/pp
}

if ! npm test
then
  echo >&2 "Testing failed"
  post_report failed
  exit 1
else
  echo "Tests passed" 
  post_report passed
fi
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.