Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm scratching my head at most of it and there's large portions that are incomplete or trivial. bash is ubiquitous. If you're trying to develop an entire web framework to run on a Bourne shell from busybox, dash, or FreeBSD 4, there's probably a better way to do it. Use the tool you have, not a hypothetical one compatible with 1983. YAGNI.

Here's a common pattern for appending to PATH system-wide once:

    # /etc/profile.d/foo.sh

    DIR=/opt/foo/bin

    case ":$PATH:" in
      *":$DIR:"*) ;;
      *) PATH="$PATH:$DIR"; export PATH ;;
    esac

    unset DIR
If zsh or bash is available:

    # $1 var
    # $2 prepend this string to var
    # $3 separator (: default if omitted)
    # doesn't remove or prevent duplicates
    prepend() {
      eval "export $1=$2\${$1:+${3-:}\$$1}"
    }

    # $1 var
    # $2 append this string to var
    # $3 separator (: default if omitted)
    # doesn't remove or prevent duplicates
    append() {
      eval "export $1=\${$1:+\$$1${3-:}}$2"
    }


Your "zsh/bash" code doesn't actually use any zsh/bash-only features, so it is compatible with POSIX sh. But you have a quoting bug: you should escape the `$` in `$2` and `${3...}` to protect from double-eval.

I'd personally try to minimise the use of eval, e.g.

    prepend() {
        local val
        eval "val=\$$1"
        export "$1=$2${val:+${3-:}$val}"
    }

    append() {
        local val
        eval "val=\$$1"
        export "$1=${val:+$val${3-:}}$2"
    }


(`local` is not in POSIX, I know)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: