简体   繁体   English

Linux Bash脚本:从用户或文件输入声明变量名

[英]Linux Bash Scripting: Declare var name from user or file input

Hi i would like to do the following. 嗨,我想做以下事情。

./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)

I know this code isn't working. 我知道此代码无法正常工作。 I need to create these temporary files and use them in a for loop later, in which i will do something with the input files and save the output in these temporary files for later usage. 我需要创建这些临时文件,并在稍后的for循环中使用它们,在该循环中,我将对输入文件进行处理,并将输出保存在这些临时文件中,以备后用。 So basically i would like to create the variable names dependent on the name of my input files. 所以基本上我想根据我的输入文件的名称来创建变量名。

I googled a lot and didn't found any answers to my problem. 我在Google上搜索了很多,但没有找到解决我问题的任何答案。

I would like to thank for your suggestions 我要感谢你的建议

I'll suggest an alternate solution to use instead of entering the variable naming hell you're proposing (Using the variables later will cause you the same problems later, the scale will just be magnified). 我将建议使用一种替代解决方案,而不是输入您要提出的变量命名方式 (以后使用变量会在以后引起相同的问题,比例会被放大)。

Use Associative arrays (like tempfile[$filename] ) instead of tempfile_"$filename" . 使用关联数组 (例如tempfile[$filename] )而不是tempfile_"$filename" That's what associative arrays are for: 这就是关联数组的用途:

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

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

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

Note: Associative arrays require bash version 4.0.0 or newer. 注意: 关联数组需要bash 4.0.0或更高版本。

If you dont have Bash version 4.0.0 or newer, see the following answers for great workarounds that dont use eval . 如果您没有Bash 4.0.0或更高版本,请参见以下答案,以获取不使用eval出色解决方法。

Try this: 尝试这个:

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

You cannot do that since Bash just doesn't allow dots in the names of identifiers/variables. 您不能这样做,因为Bash不允许在标识符/变量名称中加点。 Both of your arguments $1 and $2 have dots (periods) in them and that cannot be used in variable names you're trying to create ie tempfile_$1 参数$1$2都包含点(句点),并且不能在您要创建的变量名中使用,即tempfile_$1

See this page for details. 有关详情,请参见此页面

Use something like: 使用类似:

f1=`echo $1|tr '.' '_'`
declare "tempfile_$f1=$(mktemp)"

Check out How to define hash tables in bash? 看看如何在bash中定义哈希表?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM