Skip to content
shellhacks.dev
Testing

Set up a temp directory in Bats

Give every Bats test its own scratch directory with setup and BATS_TEST_TMPDIR. Bats creates it before the test and deletes it afterwards.

1 min read
Summarize in AI

Tests that write files interfere with each other when they share a directory, and cleanup code is easy to forget.

Shell
cat > tmp.bats <<'EOF'
setup() {
  cd "$BATS_TEST_TMPDIR"
}

@test "first test writes a file" {
  echo data > result.txt
  ls
  [ -f result.txt ]
}

@test "second test starts empty" {
  run ls -A
  [ -z "$output" ]
  echo "directory is clean" >&3
}
EOF
bats --tap tmp.bats
Text
1..2
ok 1 first test writes a file
directory is clean
ok 2 second test starts empty

Bats 1.4 and later create a fresh directory for each test and put its path in BATS_TEST_TMPDIR, as the Bats documentation lists among its special variables. setup runs before every test and here changes into it, so relative paths land in a private place that Bats removes at the end. The second test passes because it does not see the file the first one wrote. The >&3 line prints a message past Bats' output capture.

BATS_FILE_TMPDIR is shared by every test in one file and BATS_SUITE_TMPDIR by the whole run, for fixtures that are expensive to build. The directories are deleted after the run unless you pass --no-tempdir-cleanup, which helps when a test needs debugging. These variables do not exist before Bats 1.4.

Share

More snippets

Testing

Choose the shell for ShellCheck

Tell ShellCheck which shell a script targets with -s bash or -s sh. Without a shebang it cannot tell, and as sh it flags every Bash-only feature as SC3xxx.

2 min read
Testing

Skip a Bats test

Skip a Bats test with skip or skip "reason", which can be called in the middle of a test. A skipped test counts as passed, and the reason shows in the output.

2 min read
Testing

Load helpers in Bats

Share code between Bats tests with load helpers, which reads helpers.bash from the test file's directory. A plain source breaks when bats runs from elsewhere.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.