[LINUX] [Bash] Creating a safe and versatile temp directory

Introduction

--In the temporary directory creation that is usually used in the shell, the following points have been improved. --Duplicate names may occur due to direct specification such as mkdir / tmp / path. --It is not safe in terms of security because it is specified directly. --It needs to be easy to use and versatile in the process by making the name unique and adding relevance. --Therefore, this time we will describe how to create a unique, safe and versatile tmp directory.

result

--First, as a result, write the following contents in the prepared shell file.

index.sh


#!/bin/bash

basepath=$(basename $0)
timestamp=$(date +%Y%m%d%H%M%S)
tmpd=$(mktemp -dt "$basepath.$timestamp.$$")/
echo $tmpd

#output
# $TMPDIR/index.sh.20200919152709.XXXX.XXXXX/

--After writing, execute it multiple times, check the creation to the output path and non-duplicate names, and complete.

Processing content

Using the mktemp command

--By using the ** mktemp ** command to create a directory, a file or directory of size 0 is automatically created. --Click here for details on how to use mktemp Reference

Use of template options

--Use the t (template) option, which is an option specific to this command, when creating with mktemp. --By doing so, it will be automatically created in the path set in $ TMPDIR without describing the directory name. -** * When searching for the set tmp storage location, search with ʻecho $ TMPDIR** -** * If not set, specify directly with-p or store in / tmp` **

Add related items to the name

--Add something related to the name to make it easier to use when processing in the program. ――The minimum items added are as follows. --Execution path name --Timestamp (time)

Summary

――From the above, Linux has many commands to solve problems as standard, so I reconfirmed the importance of remembering and combining even one of them. ――Although it is necessary to consider safety, at the same time, I realized the importance of awareness of ease of use and versatility of processing in the program.

reference

Recommended Posts

[Bash] Creating a safe and versatile temp directory
Creating a LINE bot ~ Creating, deploying, and launching ~
Python: Creating a virtual environment (venv), starting and stopping
Try creating a compressed file using Python and zlib
Creating a graph using the plotly button and slider
Current directory when creating a new one with Jupyter