简体   繁体   中英

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

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" . 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.

If you dont have Bash version 4.0.0 or newer, see the following answers for great workarounds that dont use 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. 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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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