How do I tar a directory of files and folders without including the directory itself?

前端 未结 18 685
孤城傲影
孤城傲影 2021-01-29 17:04

I typically do:

tar -czvf my_directory.tar.gz my_directory

What if I just want to include everything (including any hidden system files) in my_

18条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-29 17:55

    This Answer should work in most situations. Notice however how the filenames are stored in the tar file as, for example, ./file1 rather than just file1. I found that this caused problems when using this method to manipulate tarballs used as package files in BuildRoot.

    One solution is to use some Bash globs to list all files except for .. like this:

    tar -C my_dir -zcvf my_dir.tar.gz .[^.]* ..?* *
    

    This is a trick I learnt from this answer.

    Now tar will return an error if there are no files matching ..?* or .[^.]* , but it will still work. If the error is a problem (you are checking for success in a script), this works:

    shopt -s nullglob
    tar -C my_dir -zcvf my_dir.tar.gz .[^.]* ..?* *
    shopt -u nullglob
    

    Though now we are messing with shell options, we might decide that it is neater to have * match hidden files:

    shopt -s dotglob
    tar -C my_dir -zcvf my_dir.tar.gz *
    shopt -u dotglob
    

    This might not work where your shell globs * in the current directory, so alternatively, use:

    shopt -s dotglob
    cd my_dir
    tar -zcvf ../my_dir.tar.gz *
    cd ..
    shopt -u dotglob
    

提交回复
热议问题