2
\$\begingroup\$

I'm new to sh and I would like to get feedback on how I can improve my code.

The purpose is simple; I want to open the Jenkins JOB related to a service based on its possible aliases. If I map a service with its aliases, READ_JOB="rj readjob read-job", I want to open it by calling the script opendeploy readjob or opendeploy rj.

The link between aliases and URLS to open was easy; an associative array worked. But I wanted to link: Service Name, Job URL and Possible Services Aliases. I Google to see if this can be done. But it looks like sh does not support nested arrays. I have created 2 arrays with the same keys.

#!/bin/bash

__READ_JOB="db-restore"

##Services x Aliases
declare -A SERVICES=(
    ["${__READ_JOB}"]="rj readjob read-job"
)

#Services x Jobs Links
declare -A JOBS_URL=(
    ["${__READ_JOB}"]="https://relatedJobUrl.com"
)

function opendeploy(){
  build=0
  rootJenskinsUrl='https://defaultUrlIfNoParameters.com/'
  urlToOpen=$rootJenskinsUrl
    while [ "$1" != "" ]; do
      __getJobLink "$1"
          if [ "$1" = -b ] || [ "$1" = --build ]; then
            build=1
          fi
          if [ "$1" = -h ] || [ "$1" = --help ]; then
            ##Calling the method that explains how to use if the user use the "-h or -help"
            __usage
            return
          fi
      shift
  done

    ##Checking if -b parameter was filled, so we can append a build parameter at the end of the url
    if [ "$build" = "1" ] && [ "$urlToOpen" != "$rootJenskinsUrl" ]; then
      urlToOpen+='/build?delay=0sec'
    fi

  open $urlToOpen
}

__usage()
{
    ##This is why I need the association with the service name to well display: Service - Possible Aliases
    echo "usage: opendeploy service [[ [-b]] | [-h]]\n (no parameters opens root Jenkins URL)\n"

    echo "Possible Services - Aliases:\n"
    for k in "${(@k)SERVICES}"; do
      echo "$k -" "$SERVICES[$k]"
    done

}

function __getJobLink() {
    for k in "${(@k)SERVICES}"; do
      for alias in $SERVICES[$k]
      do
        if [ "$alias" = "$1" ]; then
          urlToOpen=${JOBS_URL[$k]}
        fi
      done
    done
}

I see points of improvements:

  • Not to use global variables at the beginning of the script.
  • Find a way to not create 2 associative arrays.

PS: This is running in a ZSH profile. I needed to adapt because bash was not recognising some things.

I do not wait to someone 'solve it' for me. I want suggestions on what I could do to improve my code.

\$\endgroup\$
0

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.