DEV Community

t-o-d
t-o-d

Posted on

1 1

【Bash】Creating a secure and versatile temp directory

Introduction

  • The code for making tmp directory, which is usually used in shell, has the following points to be improved.
    • Because of the direct specification such as mkdir /tmp/path, the names will be duplicated in some cases.
    • Because of the direct designation, it is not secure in terms of security.
    • The names need to be unique and also add relevance so that they are easy to use and generic within the process.

Result.

  • First, we describe the following contents in the shell file we have prepared as a result.
#!/bin/bash

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

# Outputs
# $TMPDIR/index.sh.20200919152709.XXXX.XXXXX/
  • After describing it, run it multiple times to check for creation and non-overlapping of names in the output path, and you're done.

Using the mktemp command

  • You can use the mktemp command to create a directory, it creates files and directories of size 0 automatically.
    • For more information on how to use mktemp, please refer to Reference

Use of Template Options

  • When creating with mktemp, use the t(template) option, which is specific to this command.
  • By doing so, the directory will be created in the path set in the $TMPDIR automatically without specifying the directory name.
    • ※To find the configured tmp directory, use echo $TMPDIR.
    • ※If it is not set, it is specified directly by -p or stored in /tmp.

Add related items to the name

  • Add anything relevant to the name to make it easier to use when processing it in the program.
  • At a minimum, we have added the following.
    • Execution path name
    • Timestamp (time)

参考

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay