Below you will find pages that utilize the taxonomy term “Bash”
Bash practices - Part 2: CQS and return values
As I promised in my previous “Bash practices” post, I would discuss a query function in this article. Here you have it:
function create_temporary_directory() {
directory=$(mktemp -d "$1/XXXXX")
}
create_temporary_directory
echo "$directory"
That’s a bad query function!
This function is supposed to return the path of a temporary directory. It accepts one argument: an existing directory we want to create the temporary directory in. It uses the mktemp utility to do the “heavy” lifting. It accepts as an argument a kind of a template for directory names (XXXXX
will be replaced by 5 random characters). After creating the directory, mktemp
echos the full path of the directory to stdout
, meaning we can copy it into a variable by using the $(...)
syntax.
Bash practices - Part 1: Input validation and local variables
Forgive me for my bad pun. As I mentioned in my previous Bash post I’m going to show you some ways in which you can improve the design of Bash scripts. Again, it’s a weird language, and a lot of what’s below probably won’t feel natural to you. Anyway, there we go.
I started out with a piece of code that looked like this:
BUILD_DIR="build"
function clean_up() {
rm -r "$BUILD_DIR"
}
clean_up
Function arguments
Inside a function you can use all global and environment variables, which easily leads to smelly code like this: clean_up
will behave differently based on what’s in the global variable BUILD_DIR
. This makes the function itself quite unpredictable, but also error-prone, as the value of BUILD_DIR
may at one point not contain the name of a directory, or even be an empty string. Usually we would fix this by providing the path to the directory we’d like to remove as an argument of the function call, like this:
Adventures with Bash
A bit of reminiscing
When I was a kid, MS Windows was still a program called WIN.COM
which you needed to start from the MS-DOS command prompt. You could also add it to AUTOEXEC.BAT
which was a so-called batch file. You could write these .BAT
files yourself. They were basically just command-line scripts. You could make them execute commands, print things, collect input, and make simple decisions. It wasn’t much, and I remember that you often needed some helper .COM
or .EXE
programs to accomplish anything useful. The most advanced thing I ever wrote was a nice little ASCII-art menu program, spread across multiple .BAT
files (with GOTO
s and all), which allowed me to easily start my favorite games, like Super Tetris, known to me as SUPERTET.EXE
, or Prince of Persia.