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.
Tests that write files interfere with each other when they share a directory, and cleanup code is easy to forget.
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.bats1..2
ok 1 first test writes a file
directory is clean
ok 2 second test starts emptyBats 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.