Linux Bash 脚本 : Declare var name from user or file input

标签 linux bash variables scripting

您好,我想执行以下操作。

./script.sh some.file.name.dat another.file.dat

Filename1=$(echo "$1"|cut -d '.' -f 1,2)
Filename2=$(echo "$2"|cut -d '.' -f 1,2)

tempfile_"$1"=$(mktemp)
tempfile_"$2"=$(mktemp)

我知道这段代码不起作用。我需要创建这些临时文件并稍后在 for 循环中使用它们,在循环中我将对输入文件执行一些操作并将输出保存在这些临时文件中以供以后使用。所以基本上我想根据输入文件的名称创建变量名称。

我在谷歌上搜索了很多,但没有找到我的问题的任何答案。

谢谢你的建议

最佳答案

我会建议使用替代解决方案,而不是进入您提议的变量命名 hell (稍后使用变量会导致您以后遇到同样的问题,规模只会被放大) .

使用关联数组(如tempfile[$filename])而不是tempfile_"$filename"。这就是关联数组的用途:

declare -A tempfile
tempfile[$1]=$(mktemp)
tempfile[$2]=$(mktemp)

cat ${tempfile[$1]}
cat ${tempfile[$2]}

rm -f ${tempfile[$1]}
rm -f ${tempfile[$2]}

注意:关联数组需要 bash 4.0.0 或更新版本。

如果您没有 Bash 版本 4.0.0 或更高版本,请参阅以下答案以获得不使用 eval 的出色解决方法。

关于Linux Bash 脚本 : Declare var name from user or file input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17590825/

相关文章:

python - 如何在 Python 中解析 Linux 终端错误消息?

linux - 创建空文件,提示文件是否已存在?

c++ - 用宏形成变量名

c++ - 包含多个变量的字符串或函数 (c++)

python - 使用Python将变量从一个类实例传递到另一个类实例?

linux - Linux 上的 eclipse-ee : Refusing to initialize GTK+

c# - 是否可以在 Linux 中从 Python 调用 C# dll?

linux - AWK:从另一个文件添加新字段

bash - 如何将参数转发给 bash 脚本中的其他命令?

linux - 使用 grep 提取值