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

前端 未结 18 642
孤城傲影
孤城傲影 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:50
    tar -C my_dir -zcvf my_dir.tar.gz `ls my_dir`
    
    0 讨论(0)
  • 2021-01-29 17:51

    Use pax.

    Pax is a deprecated package but does the job perfectly and in a simple fashion.

    pax -w > mydir.tar mydir
    
    0 讨论(0)
  • 2021-01-29 17:51
    function tar.create() {
            local folder="${1}"
            
            local tar="$(basename "${folder}")".tar.gz
            
            cd "${folder}" && tar -zcvf "../${tar}" .; cd - &> /dev/null
    }
    

    Example:

    tar.create /path/to/folder
    

    You are welcome.

    0 讨论(0)
  • 2021-01-29 17:52

    You can also create archive as usual and extract it with:

    tar --strip-components 1 -xvf my_directory.tar.gz
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题