Linux常用命令-mktemp

命令

mktemp

描述

create a temporary file or directory
创建临时文件或目录

用法

1
mktemp [OPTION]... [TEMPLATE]

选项

1
2
3
4
5
6
Options:
-d 创建目录,默认为创建文件
-u 不创建任何文件或目录,仅仅显示名称
-q 静默模式,如果文件或目录创建失败也不提示
-p 指定目标目录,目录必须存在,可以是相对路径或绝对路径
--suffix=SUFF 指定文件后缀,使用此选项时TEMPLATE文件名必须以X结尾,如test-XXX

注意

TEMPLATE指定的文件名最少包括3个大写的X,如XXX,XXX.txt,test-XXXXX,test-XXX.txt,dir.XXXX
默认生成的文件权限为600,目录权限为700,需要通过chmod自行更改文件权限

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# 默认不加路径或文件名的话,会自动在/tmp目录下创建文件或目录
$ mktemp
/tmp/tmp.7ODnwVgSnh
$ ll /tmp/tmp.7ODnwVgSnh
-rw------- 1 root root 0 Feb 10 18:35 /tmp/tmp.7ODnwVgSnh
$ mktemp -d
/tmp/tmp.r1Jg5c3Ywr
$ ll -d /tmp/tmp.r1Jg5c3Ywr
drwx------ 2 root root 6 Feb 10 18:38 /tmp/tmp.r1Jg5c3Ywr/
# -u仅仅显示临时文件名称
$ mktemp -u test.XXX
./test.kJq
$ ls
# 文件名最少3个大写的X
$ mktemp test.X
mktemp: too few X's in template 'test.X'
$ mktemp test.x
mktemp: too few X's in template 'test.x'
# 在当前目录下创建临时文件或目录
$ mktemp a.XXX
a.PJY
$ mktemp a.XXX
a.2sQ
$ mktemp -d dir.XXX
dir.fip
$ mktemp -d dir.XXX
dir.PNg
$ ll
-rw------- 1 root root 0 Feb 10 18:52 a.2sQ
-rw------- 1 root root 0 Feb 10 18:51 a.PJY
drwx------ 2 root root 6 Feb 10 18:52 dir.fip/
drwx------ 2 root root 6 Feb 10 18:52 dir.PNg/
# 指定相对路径目录,不支持自动创建目录
$ mktemp -p dir1 b.XXXX
mktemp: failed to create file via template ‘dir1/b.XXXX’: No such file or directory
$ mkdir dir1
$ mktemp -p dir1 b.XXXX
dir1/b.bJpo
$ mktemp -p dir1 b.XXXX
dir1/b.g0L1
$ ll dir1
-rw------- 1 root root 0 Feb 10 18:56 b.bJpo
-rw------- 1 root root 0 Feb 10 18:56 b.g0L1
# 指定绝对路径目录
$ mkdir /tmp/test
$ mktemp -p /tmp/test/ test.XXX
/tmp/test/test.NEh
$ mktemp -p /tmp/test/ test.XXX
/tmp/test/test.dCv
$ ll /tmp/test/
-rw------- 1 root root 0 Feb 10 18:57 test.dCv
-rw------- 1 root root 0 Feb 10 18:57 test.NEh
# 也可以省略-p选项,直接指定目录路径加文件名
$ mktemp dir1/XXXXX
dir1/8cbMW
$ mktemp /tmp/test/XXX
/tmp/test/ylw
# 追加后缀
$ mktemp --suffix=txt b.XXX
b.0tGtxt
$ mktemp --suffix=txt b.XXX
b.pw8txt
$ ll b*
-rw------- 1 root root 0 Feb 10 19:00 b.0tGtxt
-rw------- 1 root root 0 Feb 10 19:00 b.pw8txt
# 替换后缀
$ mktemp --suffix=.txt XXX
Cyp.txt
$ mktemp --suffix=.txt XXX
XTa.txt
$ ll *.txt
-rw------- 1 root root 0 Feb 10 19:04 Cyp.txt
-rw------- 1 root root 0 Feb 10 19:04 XTa.txt

# 随机文件名
$ mktemp XXX
W4a
# 随机后缀
$ mktemp a.XXX
a.H8Q
# 指定后缀
$ mktemp XXX.txt
5zS.txt
$ mktemp --suffix=.txt XXX
clu.txt
# 指定前缀和后缀
$ mktemp test-XXX.txt
test-er4.txt
$ mktemp --suffix=.txt test-XXXXX
test-CBWlW.txt
# 此选项要求文件名必须以X结尾
$ mktemp --suffix=txt test-XXXXX.
mktemp: with --suffix, template ‘test-XXXXX.’ must end in X