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

前端 未结 18 664
孤城傲影
孤城傲影 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条回答
  •  日久生厌
    2021-01-29 17:56

    I would propose the following Bash function (first argument is the path to the dir, second argument is the basename of resulting archive):

    function tar_dir_contents ()
    {
        local DIRPATH="$1"
        local TARARCH="$2.tar.gz"
        local ORGIFS="$IFS"
        IFS=$'\n'
        tar -C "$DIRPATH" -czf "$TARARCH" $( ls -a "$DIRPATH" | grep -v '\(^\.$\)\|\(^\.\.$\)' )
        IFS="$ORGIFS"
    }
    

    You can run it in this way:

    $ tar_dir_contents /path/to/some/dir my_archive
    

    and it will generate the archive my_archive.tar.gz within current directory. It works with hidden (.*) elements and with elements with spaces in their filename.

提交回复
热议问题