Tar: create archive exclude directories except one

One way would be first excluding the mydir and then appending the my_archive_dir

tar cvf dir_archive.tar --exclude=dir_archive/mydir dir_archive
tar rvf dir_archive.tar dir_archive/mydir/my_archive_dir
gzip dir_archive.tar

Unfortunately appending doesn't work with zipped archives.

The --exclude option takes a pattern as argument, so if the names of the dirs to be excluded are similar, you can avoid them and still include the archive dir

tar cvfz dir_archive.tar.gz --exclude=dir_archive/mydir/exclude* dir_archive

It is also possible to create a file with names of all the files that you want included and give that list to tar with option -T or --files-from (or in similar fashion list the files to be excluded and give the list with option -X).

filelist.txt:
dir_archive
dir_archive/temp1
dir_archive/mydir
dir_archive/mydir/temp2
dir_archive/mydir/my_archive_dir
dir_archive/mydir/my_archive_dir/temp7
tar cvfz dir_archive.tar.gz --no-recursion --files-from filelist.txt

Order matters:

$ mkdir -p dir_archive/{somedir{1..3},mydir/{excludedir{1..3},otherone,my_archive_dir}}
$ touch dir_archive/{somedir{1..3},mydir/{excludedir{1..3},otherone,my_archive_dir}}/dir_file.txt
$ tar cvzf dir_archive.tar.gz dir_archive/mydir/my_archive_dir* --exclude "dir_archive/mydir/*" dir_archive
dir_archive/mydir/my_archive_dir/
dir_archive/mydir/my_archive_dir/dir_file.txt
dir_archive/
dir_archive/mydir/
dir_archive/somedir2/
dir_archive/somedir2/dir_file.txt
dir_archive/somedir1/
dir_archive/somedir1/dir_file.txt
dir_archive/somedir3/
dir_archive/somedir3/dir_file.txt

What this is doing in essence is being more explicit up front, then applying the exclude to the parent directory only.

Stolen shamelessly from https://unix.stackexchange.com/a/417707/420501