For a research analysis, I'm writing a small bash script that serves as a frontend to Singularity. The reason is that I want to save in this script which options are needed for singularity. For example, I want the working directory to appear at a fixed path in the container, regardless of the actual working directory path.
Singularity has the
--contain option for this, but this requires me to manually define a temporary directory for the container. I use
mktemp for that. After the end of the script, I use
delete that directory. However, I fear that there might be a corner case where
trap "rm -rf '$tmpdir' might delete the wrong directory.
The script, called
cexec, executes an arbitrary command inside the container. For example
./cexec R starts R inside the container.
Is there a corner case in the following script where the script deletes a directory that it didn't create?
#!/bin/bash # Execute a command in the container set -ue thisdir="$(dirname "$BASH_SOURCE")" container="rserver_200211_commitd117c677.sif" # get such a file by using `singularity pull ...` # Create a temporary directory tmpdir="$(mktemp -d -t cexec-XXXXXXXX)" # We delete this directory afterwards, so its important that $tmpdir # really has the path to an empty, temporary dir, and nothing else! # (for example empty string or home dir) if [[ ! "$tmpdir" || ! -d "$tmpdir" ]]; then echo "Error: Could not create temp dir $tmpdir" exit 1 fi # check if temp dir is empty tmpcontent="$(ls -A "$tmpdir")" if [ ! -z "$tmpcontent" ]; then echo "Error: Temp dir '$tmpdir' is not empty" exit 1 fi # Delete the temporary directory after the end of the script trap "rm -rf '$tmpdir'" EXIT singularity exec \ -B "$tmpdir:/tmp" \ --contain \ -H "$thisdir:/data" \ "$container" \ "$@"