I have a bash script that has 13 variables and runs commands on them.
I've copied the commands 13 times but I'd like to simplify it to simply add 1 to the previous and run 13 times.
The variables are
dir01=/path/to/dir01
dir01=/path/to/dir02
... up to 13. (more may be added later)
...
# executable stuff
mkdir "$dir01/".LogFiles
cp -R "$dir01"/*.aep\ Logs "$dir01"/.LogFiles/
rm -Rf "$dir01"/*.aep\ Logs "$dir01"/*.log
echo 01
mkdir "$dir02/".LogFiles
cp -R "$dir02"/*.aep\ Logs "$dir02"/.LogFiles/
rm -Rf "$dir02"/*.aep\ Logs "$dir02"/*.log
echo 02
# repeated 13 times for each dir.
I'd like to simplify it to something like this:
n=1 # Amount to add each time
num=00 # Base number to start with
while [ x = 0 ]
do
workon=$dir(($num += $n))
mkdir "$workon/".LogFiles
cp -R "$workon"/*.aep\ Logs "$workon"/.LogFiles/
rm -Rf "$workon"/*.aep\ Logs "$workon"/*.log
echo "$workon"
x=1
done
I don't know how to get it to stop when it's done 13 or whatever number of variables I have.
BTW I'm using cp and rm because mv won't clobber a directory.
These are render log files that are annoying and mostly useless so I don't mind overwriting files.
I defined paths for dir1 through dir13 as variables but I can't get the loop to add the number to the "dir" to create "dir1" and then use it as the defined variable.
This is my test code:
######################################
# dir1 through dir13 defined previously
n=1
num=1
run=13 # How many directories are we working on?
(( run += n )) # Add one to the number of directories
################################
while (( $num < $run ))
do
echo $dir$num
(( num += n )) # When num = run exit loop
done
Instead of echoing the defined path for variable "dir1, dir2 ..." it echos "dir1" and "dir2," literally.
If I echo "$dir1" by adding it manually, I get the defined path as desired.
Why won't $dir$num echo as the path?
Variables don't work that way. Dynamic variable names are discouraged in general -- that's the sort of thing you should be using an array or even just a space-separated string for.
You can dereference a variable name with ${!...} however. (This is a BASH-only feature.)
How can I set a variable with a space in it?
"dir 1" and "dir\ 1" don't work.
I'm interested if having spaces in the variable definition would also work.