You didn't specify the working environment, and although it seems to be bash/GNU I thought the following solution was sufficiently interesting to throw into the melting pot. It uses the BSD version of tar(1)
(usually available as bsdtar
on non-BSD platforms), and uses its @<mtree>
feature to provide the archive content specification in mtree
format.
awk -v tmpdir=`mktemp -d` -v tmpfile=`mktemp` -v uid=`id -u` -v gid=`id -g` 'BEGIN {print "#mtree"; print "/set uid=" uid " gid=" gid " mode=755"; for(d=1;d<=50;d++) {printf "dir-%02d type=dir content=%s\n", d, tmpdir; for(f=1;f<=50;f++) printf "%02d.txt type=file content=%s\n", f, tmpfile; print "..";}}' | tar cf final.tar @-
Split up for easier reading:
awk -v tmpdir=`mktemp -d` -v tmpfile=`mktemp` -v uid=`id -u` -v gid=`id -g` \
'BEGIN {print "#mtree"; print "/set uid=" uid " gid=" gid " mode=755"; \
for(d=1;d<=50;d++) {printf "dir-%02d type=dir content=%s\n", d, tmpdir; \
for(f=1;f<=50;f++) printf "%02d.txt type=file content=%s\n", f, tmpfile; \
print "..";}}' \
| tar cf final.tar @-
Explanation
- Uses the
mktemp(1)
utility to (safely) create empty source directory and source file
- The
/set
mtree directive defines the default uid/gid/mode
- The
content=
attribute specifies the source content for each dir/file as the temp copy
@-
reads the mtree spec from stdin
- Leaves the
mktemp
files for the system to clean up (since, by default, they're created in the system "temp" directory - normally $TMPDIR
or /tmp
)
Remove the trailing | tar ...
to see the mtree spec that is generated.
Of course, substitute bsdtar
for tar
as needed.
The key features of this approach are using mktemp
to safely create the temporary file and directory (which avoids having to worry about conflicts with existing files and finding a safe/suitable location to create them) and only having to create one of each for any number of directories or files.
dir-01/01.txt
and so on, you have to use{01..50}
. Btw, you don't need a loop at all:mkdir dir-{.1..50} && touch dir-{01..50}/{00..50}.txt
would do the job as well. If you are trying to build atar
bomb, the files should not be empty though. (-;