Hello, I am a new joiner to the forum, and have what i hope is a simple question, however I can't seem to find the answer so maybe it is not available within bash scripting.
I intend to use the below script to archive files from multiple directories at once by using a loop, and a variable (n) which increases by one each loop.
The problem is that when i connect two variables, if i define a variable with that output, it is not called, only the text is output.
Hopefully you can see what im trying to do and it will explain itself;
#!/bin/bash
n=1
a=/archive
dir_1=/home/gohara/test/sd1
dir_2=/home/gohara/test/sd2
dir_3=/home/gohara/test/sd3
filemask_1=TAV*.???
filemask_2=TAV*.???
filemask_3=TAV*.???
fileage_1=30
fileage_2=30
fileage_3=30
while [ $n -le 3 ]
do
#If dir_n is NOT NULL
if [ -n $dir_$n ]; then
find $dir_$n/$filemask_$n -type f -mtime +fileage_$n -exec mv {} $dir_$n$a \;
#Repeat task for 3 directories listed above
n=`expr $n + 1`
fi
done
#!/bin/bash
n=1
a=/archive
dir_1=/home/gohara/test/sd1
dir_2=/home/gohara/test/sd2
dir_3=/home/gohara/test/sd3
filemask_1='TAV\*.???' # avoid interpolation here
filemask_2='TAV\*.???' # And include an escape
filemask_3='TAV\*.???'# for the call to find
fileage_1=30
fileage_2=30
fileage_3=30
while [ $n -le 3 ]
do
#If dir_n is NOT NULL
if [ -n ${dir_$n} ]; then
find ${dir_$n}/${filemask_$n} -type f -mtime +fileage_$n -exec mv {} ${dir_$n}$a \;
#Repeat task for 3 directories listed above
n=`expr $n + 1`
fi
done
You can surround the variable name with braces to isolate it from surrounding text.
I've only just tested what you mentioned which workeda treat!
Now I have to try and utilise it multiple times for multiple variables throughout the script.
I havent yet attempted the array but I might give it a go this week.
Once done I'll post a copy of the finished script as i havent been able to find one similar in the forums.
Back to Post #1. If you really want to do it this way, then you need to use a Shell "eval" statement wherever you are changing the name of an environment variable on the fly. This further involves escaping certain $ symbols to protect them from the Shell first pass.
On a design point it would be much easier to read a flat file of records with each records containing the three parameters. The script would then work for a virtually unlimited number of records.
Thanks again for your help above, much appreciated.
I'm now trying to use the eval statement as advised above before attempting an array.
Can anyone tell me what i'm doing wrong? I sort of understand the method behind the eval command but haven't been able to use it successfully with the below script...
It should be self explanatory what im trying to acheive, any help would be appreciated. Thanks!