r/bash • u/triscalade • 23d 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
View all comments
1
u/michaelpaoli 22d ago
You're squashing all your arguments after first into a single argument. That's probably not what you want.