如何通过 Tcl 语言创建临时 shellscript 文件和目录?



有很多方法可以做到这一点,我在这里介绍的方法就是其中之一,使用许多Linux发行版中默认安装的"mktemp"工具。

临时文件和目录

">

mktemp"工具默认在"GNU coreutils"软件包中,其目的只是创建临时文件/目录。

创建临时文件

和临时文件

它的基本用途非常简单。从命令行调用"mktemp"而不带任何参数将在/tmp内的磁盘上创建一个文件,其名称将显示在屏幕上。看:

$ mktemp
/tmp/tmp.JVeOizVlqk

创建目录就像在命令行中添加"-d"参数一样简单。

$ mktemp -d
/tmp/tmp.sBihXbcmKa

在实践中使用

实际上,屏幕上显示的临时文件或目录名称是没有用的。它必须存储在一个变量中,该变量可以随时访问,并且可以在处理过程中读取或写入。

在下面的示例中,有一个小脚本,顺便说一下没用,但它向我们展示了一个合适的分步。看:

#!/bin/sh
#
#Create a temporary file
TEMP = `mktemp`
#Save all the content of the entered path
ls -l "$1"> $TEMP
#Read temporary file and list only directories
grep ^d $TEMP
sudo rm -f $TEMP

请注意,命令"mktemp"是在子shell中调用的(在"-crase"之间(,其输出存储在变量"TEMP"中。

然后,为了可以读取或写入文件,只需使用变量,其中将有文件名,如lsgreprm命令中所做的那样。

如果需要创建目录,如前所述,过程是相同的,只是在 mktemp 命令行中添加一个-d

#!/bin/sh
#
TEMP = `mktemp -d`
cd $TEMP
.
.
.
sudo rm -rf $TEMP

如果要创建许多临时文件,我们使用"-p"参数指定应创建文件的路径。

#!/bin/sh
#
TEMP = `mktemp -d`
cd $TEMP
FILE1 = `mktemp -p $TEMP`
.
.
.
sudo rm -f $FILE1
sudo rm -rf $TEMP

仅此而已。您的脚本现在可以更专业地使用临时文件。

但是,我想用tclsh而不是sh[bourn shell..]来做到这一点,但我做了几次尝试,没有任何效果。这是我尝试的示例:

# Create a temporary file
exec sh -c "TEMP =`mktemp -d`"
set dir [cd $TEMP]
# Save all content from the entered path
exec ls -l "$1"> $TEMP
set entry [glob -type f $env(dir) *.jpg]
# Read temporary file and list only directories
puts $entry

我最大的问题是创建变量

# Create a temporary file
exec sh -c "TEMP =`mktemp -d`"

这是行不通的!

有人可以给我一个免费样品吗?!

可以使用file tempfile创建临时文件。对于目录file tempdir将在 Tcl 8.7 中提供。

在 8.7 之前的 Tcl 版本上,您可以使用file tempfile获取临时位置的路径,然后使用该名称创建目录:

set fd [file tempfile temp]
close $fd
file delete $temp
file mkdir $temp

file tempfile命令还允许您指定模板,类似于mktemp的 -p 选项


要回答更新后的问题,您可以执行以下操作:

# Create a temporary file
set temp [exec mktemp]
# Save all content from the entered path
exec ls -l [lindex $argv 0] > $temp
# Read temporary file
set f [open $temp]
set lines [split [read $f] n]
close $f
# List only directories
puts [join [lsearch -all -inline $lines {d*}] n]

我忽略了您将目录和常规文件以及 *.jpg 应该是什么的混淆。

您尝试从 Tcl 内部创建 shell 变量,然后在下一个exec命令中使用它们将始终失败,因为当第一个子 shell 终止时,这些变量将消失。将结果保留在 Tcl 变量中,就像我上面所做的那样。

当然,您可以使用glob -type d更轻松地找到目录,但我保留了shell命令作为示例。


例如,创建目录临时 这将是这样的:

# Create a temporary directory
set dir [exec mktemp -d] ; 
# Now, files insert in directory 
# (In this example I am decompressing a ZIP file and only JPEG format images)
exec unzip -x $env(HOME)/file.zip *.jpg -d $dir ; 
# Look the directory now with this command:
puts [glob -nocomplain -type f -directory $dir -tails *.jpg] ; 

最新更新