While building Rust Adventure (a temporary name for a Rust course I'm working on), I found running
cargo new repeatedly, so I decided to automate it with bash.
fd, we can see a sample layout for the project. In
./adventures we have a set of cargo crates as a workspace.
First in our script we set the
shebang, aka the
#!, to use the bash interpreter. (yes it's really called that, no I don't know why).
set -euxo pipefail, which other people have already explained well. TLDR; it makes our bash script a bit safer to run, and prints each command as it executes.
Now we start getting into our script logic. We set
LAST_FILE equal to the last result in a sorted list created by
fd. This gives us the "highest number" in the filenames, since they're effectively sorted by number.
fd is looking for directories (
-t d) one level deep (
-d 1) in
adventures that match
We want to get the highest number from the list of directories and increment it. To do this we'll use regex. To regex in bash, we can set up our regex as a variable with a string. This looks for any numbers after
adventures/a- and puts them in a capture group.
Then test our filename against the regex to see if it matches.
I put the capture group result into a new variable
number for clarity, then add
1 to it. We can overwrite the variable here because we won't be using the original again.
If we leave the number as-is, then any number below 100 won't have three digits. To fix this we can use
printf to pad the number with leading zeroes. This leaves us with numbers like
and finally we can use our variables along with a positional argument to the script to instantiate our
The output could look like this.