If you know for a fact directory names do not contain whitespace you could use a pair of arrays, eg:
DIRS[1]="foo bar live1 live2"
SRCDIR[1]="/mnt/nas/stage/live/live/"
DIRS[2]="test1 test2"
SRCDIR[2]="/mnt/nas/stage/test/test/"
for ((id=1; id<=2; id++))
do
for dir in ${DIRS[id]} # no double quotes so that each entry is processed separately
do
echo "${SRCDIR[id]}${dir}"
done
done
This generates:
/mnt/nas/stage/live/live/foo
/mnt/nas/stage/live/live/bar
/mnt/nas/stage/live/live/live1
/mnt/nas/stage/live/live/live2
/mnt/nas/stage/test/test/test1
/mnt/nas/stage/test/test/test2
If directory names could contain whitespace this solution (unquoted ${DIRS[id]}
) does not work, consider:
DIRS[1]="foo bar live1 live2 'foo bar live{1,2}'" # 5th entry contains a pair of spaces
SRCDIR[1]="/mnt/nas/stage/live/live/"
DIRS[2]="test1 test2"
SRCDIR[2]="/mnt/nas/stage/test/test/"
for ((id=1; id<=2; id++))
do
for dir in ${DIRS[id]} # split on whitespace
do
echo "${SRCDIR[id]}${dir}"
done
done
This generates:
/mnt/nas/stage/live/live/foo
/mnt/nas/stage/live/live/bar
/mnt/nas/stage/live/live/live1
/mnt/nas/stage/live/live/live2
/mnt/nas/stage/live/live/'foo # 5th entry
/mnt/nas/stage/live/live/bar # broken into
/mnt/nas/stage/live/live/live{1,2}' # 3 parts
/mnt/nas/stage/test/test/test1
/mnt/nas/stage/test/test/test2
If directory names can contain white space then another approach would be to use hard-coded array names and namerefs (declare -n
), eg:
DIRS1=(foo bar live1 live2 'foo bar live{1,2}') # 5th entry contains a pair of spaces
SRCDIR1="/mnt/nas/stage/live/live/"
DIRS2=(test1 test2)
SRCDIR2="/mnt/nas/stage/test/test/"
for ((id=1; id<=2; id++))
do
declare -n dirs="DIRS${id}" # nameref; 1st time dirs is a pointer to DIRS1
declare -n srcdir="SRCDIR${id}" # nameref; 1st time srcdir is a pointer to SRCDIR1
for dir in "${dirs[@]}"
do
echo "${srcdir}${dir}"
done
done
NOTE: namerefs require bash 4.2+
This generates:
/mnt/nas/stage/live/live/foo
/mnt/nas/stage/live/live/bar
/mnt/nas/stage/live/live/live1
/mnt/nas/stage/live/live/live2
/mnt/nas/stage/live/live/foo bar live{1,2} # 5th entry maintains whitespace
/mnt/nas/stage/test/test/test1
/mnt/nas/stage/test/test/test2
As mentioned in comments, the ideal solution would be a pair of multi-dimensional arrays (eg, DIRS[1,1]="foo"
); unfortunately bash
does not support multi-dimensional arrays.
Yes, it is possible to simulate a multi-dimensional array via concatenation of indices (eg, DIRS[1-1]="foo"
) but the necessary code gets a bit messy. I'll leave it to OP to research this idea if it's of interest ...