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\$
  • 5
    \$\begingroup\$ Please specify what this code accomplishes, and retitle the question accordingly. See How to Ask. \$\endgroup\$ – 200_success Feb 28 '19 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.