|
|
|
|
|
by godelski
538 days ago
|
|
> Bash: ensure exactly two params are passed, 1st one is a dir, 2nd is a file, enter" than to type the code directly
This seems much simpler than you made it out to be. Why not use ${#FOO[@]} for the number of args.If you have strict ordering, your program is just as fast to type as it is to ask cursor (imo) [[ $# == 2 && -d "$1" && -a "$2" ]] || exit 2
alternatively conditionally assigning
[[ $# == 2 && -d "$1" && -a "$2" ]] && PREFIX="$1" && FILE="$2" || exit 2
I'll give you that it is probably faster if you are wanting to write it more correct and be order invariant (not what you asked), but with boiler plate I often just use macros.I'm curious, what is Cursor's solution? Here's a pretty quick way that leaves some room for expandablity #!/usr/bin/env bash
declare -ri MAXARGS=2
declare -rA ECODES=(
[GENERAL]=1
[BADARGS]=2
)
FILE=
PREFIX=
fail_with_log() {
echo "$1"
exit ${ECODES[$2]}
}
check_args() {
[[ $# == $MAXARGS ]] \
|| fail_with_log "Wrong number of arguments, expected ${MAXARGS} got $#" "BADARGS"
# We might want to use -f instead of -a
# Check if PREFIX + FILE or FILE + PREFIX
if [[ -d "$1" && -a "$2" ]];
then
PREFIX="$1"
FILE="$2"
elif [[ -a "$1" && -d "$2" ]];
then
FILE="$1"
PREFIX="$2"
else
fail_with_log "Must provide both a file and a directory" "BADARGS"
fi
}
main() {
check_args "$@"
...
}
main "$@" || exit ${ECODES["GENERAL"]}
I mean a bunch of stuff above are superfluous but it doesn't take long to write (can be macro'd) and that little bit adds some flexibility if we want to extend down the line.
There's of course, many ways to write this too. We could use a loop to provide more extensibility or even more conditional assignments. But this feels clearer, even if not very flexible. |
|
Re: macros: Cursor works this way as a shortcut for all manner of boring code in any programming language and for this kind of thing is very trustworthy. Using it leaves me more mental energy to spend on other things. Macros (I think I call this "snippets"?) are only worth it for frequently repeated tasks.
This is what that prompt produces. Besides putting the count check first, it's what I would have written myself: