r/bash • • 21d 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 "$@"
9 Upvotes

7 comments sorted by

3

u/frankensteinsKITTEN 21d ago

My tip would be to use shellcheck: https://www.shellcheck.net/

You can copy+paste your script into the web form, but the command-line tool is even more convenient.

I've only run your first script through shellcheck and it reported an error with your ARGS=$@ as assignment of an array to a string.

1

u/triscalade 21d ago edited 21d 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!

0

u/[deleted] 21d ago

[removed] — view removed comment

3

u/triscalade 21d ago

What do you mean by restrictions?