mktemp with extension without specifying file path

1.4k Views Asked by At

Prefacing this with that I found identical questions but none of them have answers that are working for me.

I need to make a temporary .json file (it needs to be json because I'll be working with jq later in the script).

I thought based on the answers to this question that it would be the following, but they're creating files named .json and XXXXXXXX.json respectively.

STACKS=$(mktemp .json)
STACKS=$(mktemp XXXXXXXX.json)

This will need to run on both mac OS, and a linux box. I can't specify a path for the file because it will be run both locally and by Jenkins, which have an unidentical file structure. What's the proper syntax?

1

There are 1 best solutions below

13
On BEST ANSWER

if you are using openBSD mktemp you can

STACKS="$(mktemp XXXXXX).json"

and then write a trap so the tmps are removed when script finishes:

function cleanup {
    if [ -f "$STACKS" ] && [[ "$STACKS" =~ ".json"$ ]]; then
        rm -f "$STACKS"
    fi
}
trap cleanup EXIT

so when script finishes (no matter how) it will try to remove $STACKS if it is a file and if it ends with .json (for extra safety).