r/bash • • 27d ago

critique My first bash scripts

The goal for this one is to take a package (eg. cmatrix) and its arguments and input them into the nix run command like this:

nix run nixpkgs#cmatrix -- -a -b ...

#!/usr/bin/env bash
PKG=$1
shift 1
ARGS=$@
nix run "nixpkgs#$PKG" -- "$ARGS"

This goal for this one is to take multiple packages (eg. cmatrix, sl) and put them into the nix shell command like this:

nix shell nixpkgs#cmatrix nixpkgs#sl

#!/usr/bin/env bash
ARGS=""
main() {
   args "$@"
   nix shell$ARGS
}
args() {
    while [[ $# -gt 0 ]]; do
        ARGS="$ARGS nixpkgs#$1"
        shift 1
    done
}

main "$@"

Any feedback or advice would be appreciated :)

EDIT: Here is my rewrite of the second one

#!/usr/bin/env bash
set -e
set -u
set -o pipefail

enter-temporary-shell() {
    if [[ $# -lt 1 ]]; then
        echo "USAGE: $0 PACKAGE [PACKAGE...]"
        exit 1
    fi

    local -a temporary_packages=${1:?}
    temporary_packages=$(prepend-nixpkgs "$@")

    echo "Entering temporary shell with""$temporary_packages" "enabled"
    echo "Press ^D to exit"
    nix shell $temporary_packages
}
prepend-nixpkgs () {
    local -a arguments=("$@")
    echo "${arguments[@]/#/ nixpkgs#}"
}

enter-temporary-shell "$@"
8 Upvotes

7 comments sorted by

View all comments

Show parent comment

1

u/triscalade 27d ago edited 27d ago

Thanks, I didn't know about that tool. :)

EDIT: I tried it out and realized that I could just pass $@ instead of a variable so now it's a line shorter!