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

2.5k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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
0
On

mktemp exits 0 on success, and >0 if an error occurs. . try something like this. Make sure you have sufficient privileges :

 tempfoo=`basename $0`
           TMPFILE=`mktemp -d /tmp/${tempfoo}.XXXXXX`
           if [ $? -ne 0 ]; then
                   echo "$0: Can't create temp file, exiting..."
                   exit 1
           fi

So the script will give the stdr erro message in case of an exit > 0. From here you can just do && cd tempfoo and echo $PWD || echo "can not access $ tempfoo"

the rest go here ...