bashmktemp

Error with Bash Script to create a Temp directory and copy some files


I am trying to create a Temp directory, copy some file into it, do some processing, and delete the directory. So far, I have:

#!/usr/bin/env bash

__tmpdir="mktemp -d /Users/Riwaz/support.XXXXXXXXXX" #Create temp directory; store address
cp /some_location/checkstyle.xml $__tmpdir #Copy a file into the directory
cd $__tmpdir
tar -czvf result.tar.gz *
cp result.tar.gz /Users/Riwaz/
rm $__tmpdir

But when I run thus using sh, I get:

line 7: cd: mktemp: No such file or directory
rm: mktemp: No such file or directory
rm: -d: No such file or directory
rm: /Users/Riwaz/support.XXXXXXXXXX: No such file or directory

which shows that mktemp statement never gets processed and variable holds the actual command and not the address. How would I make bash evaluate the command and store the address instead? I messed around with "", {}, and eval but couldn't make it work.


Solution

  • You need to modify your script like below: First line is simply assignment instead you need to run it in sub shell and assign.

    #!/usr/bin/env bash
    __tmpdir=(mktemp -d /Users/Riwaz/support.XXXXXXXXXX) #Create temp directory; store address
    cp /some_location/checkstyle.xml $__tmpdir #Copy a file into the directory
    cd $__tmpdir
    tar -czvf result.tar.gz ./*
    cp result.tar.gz /Users/Riwaz/
    rm $__tmpdir