How to create a temporary directory?

后端 未结 4 732
借酒劲吻你
借酒劲吻你 2020-12-22 16:54

I use to create a tempfile, delete it and recreate it as a directory:

temp=`tempfile`
rm -f $temp
  # 
mkdir $temp
4条回答
  •  难免孤独
    2020-12-22 17:25

    For a more robust solution i use something like the following. That way the temp dir will always be deleted after the script exits.

    The cleanup function is executed on the EXIT signal. That guarantees that the cleanup function is always called, even if the script aborts somewhere.

    #!/bin/bash    
    
    # the directory of the script
    DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    
    # the temp directory used, within $DIR
    # omit the -p parameter to create a temporal directory in the default location
    WORK_DIR=`mktemp -d -p "$DIR"`
    
    # check if tmp dir was created
    if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
      echo "Could not create temp dir"
      exit 1
    fi
    
    # deletes the temp directory
    function cleanup {      
      rm -rf "$WORK_DIR"
      echo "Deleted temp working directory $WORK_DIR"
    }
    
    # register the cleanup function to be called on the EXIT signal
    trap cleanup EXIT
    
    # implementation of script starts here
    ...
    

    Directory of bash script from here.

    Bash traps.

提交回复
热议问题