[Nix-dev] What about making addToSearchPathWithCustomDelimiter only add uniq items?

Marc Weber marco-oweber at gmx.de
Tue Aug 25 18:22:36 CEST 2009


Purpose:

         A
      /    \
     B       C
     |       |
     D       D (B and C depend on D using propagated-build-inputs)

Then A will have D two times in PATH ?

So what about replacing the addToSearchPathWithCustomDelimiter by this
implementation only adding an item when not present?
It looks ugly but works.

  addToEnvListUniq(){
    # $1 : name
    # $2 : delimiter
    # $3 : value

    # if removing one of vale: :value: :value succeeds or value = list then don't item because its present
    [ "${!1}${!1}${!1}" == "${!1/#$3$2/}${!1/$2$3$2/}${!1/%$2$3/}" ] && [ "$3" != "${!1}" ] &&
    export ${1}="${!1}${!1:+$2}$3"
  }

  addToEnvUniq PATHX : path1
  addToEnvUniq PATHX : path1
  addToEnvUniq PATHX : path2
  addToEnvUniq PATHX : path2
  addToEnvUniq PATHX : path1

  echo $PATHX # echos path1:path2


You could implement this using the newer bash array feature. However you
have to declare the array first which is worse. You can't do this within the function
because the result will be local array only :-(

  # bad:
  # - hash can get out of sync
  # - you'll forget declare -A

  declare -A PATHX_HASH

  addToEnvUniq(){
    # $1 : name
    # $2 : delimiter
    # $3 : value
    nh=${1}_HASH

    # declare -A "$nh" << this would work if it wasn't local to this function. declared manually above

    ind="${nh}[$3]"
    [ -z "${!ind}" ] && {
      read "$ind" <<< "x" # read a char into $1[$3] to add the key
      export ${1}="${!1}${!1:+$2}$3"
    }
    echo all ${PATHX_HASH[@]}
  }

  addToEnvUniq PATHX : path1
  addToEnvUniq PATHX : path1
  addToEnvUniq PATHX : path2
  addToEnvUniq PATHX : path2
  addToEnvUniq PATHX : path1

  echo $PATHX # echos path1:path2

Marc Weber



More information about the nix-dev mailing list