2

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

Jujo
  • 79
  • 1
  • 5
  • If you `echo $Filename1 echo $Filename2` in script, output will be `some.file` and `another.file`, what seems to be the problem then? you want `some.file.name` and `another.file` – mirkobrankovic Jul 11 '13 at 10:26
  • Just use `tempfile1` and `tempfile2`, the same way you use `Filename1` and `Filename2`. – choroba Jul 11 '13 at 10:33
  • 1
    Use associative arrays, instead of this **painful** (and possibly _stupid_) way of creating variables. That's what associative arrays were introduced for. – Samveen Jul 11 '13 at 10:41
  • In the next step i use $1 $2 as iterative in my for loop like – Jujo Jul 11 '13 at 11:16

4 Answers4

1

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.

Community
  • 1
  • 1
Samveen
  • 3,482
  • 35
  • 52
  • Thank you very much! This solution will work for me. This is a great community, again Thanks for your help! – Jujo Jul 11 '13 at 11:58
0

Try this:

eval "tempfile_"$1"=$(mktemp)"
eval "tempfile_"$2"=$(mktemp)"
developer
  • 4,744
  • 7
  • 40
  • 55
0

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 i.e. tempfile_$1

See this page for details.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Use something like:

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

Check out How to define hash tables in bash?

Community
  • 1
  • 1
Dileep
  • 775
  • 5
  • 20