📜  用于创建指定目录的压缩存档的 Shell 脚本

📅  最后修改于: 2022-05-13 01:57:28.762000             🧑  作者: Mango

用于创建指定目录的压缩存档的 Shell 脚本

存档是将一组文件或文件夹存储到一个文件中的简单过程。有时我们可能需要从单个文件夹中创建一个压缩档案,以便我们可以与他人共享或用于其他目的。在 Linux 中,为了简化任务,我们可以创建一个 shell 脚本,通过仅提供文件夹名称来自动化创建存档的过程。

使用tar命令:

Tar 是 Tape Archive的首字母缩写词。它最初由 John Gilmore 于 1979 年 1 月在 AT&T 贝尔实验室创建。创建 tar实用程序的主要目的是从许多文件中有效地创建一个存档。 tar 命令从多个文件创建单个存档。这个新创建的存档也称为 tarball。 tar也可用于提取存档。

句法:

以下是一些最常用的选项:



Sr. no.Options (short forms)Options (expanded forms)Description

1.

-c

–create

To create Archive

2.

-x

–extract

 To extract one or more file(s) from the archive



3.

-f

–file=archive-name

To create an archive with a given filename/archive-name

4.

-t

–list

To list the names of all the files in the archive.

5.

-u

–update

To update the file in archives and add files to the end of the archive.

6.

-v

–verbose

To display Verbose Information.

注意:此处,archive-name 应替换为您要为存档提供的名称。

代码:

#!/bin/bash

# Here we are checking if the directory name
# is provided in the argument or not.
# -z will check for the null string 
# and $1 will check if the positional argument
# is passed or not
if [ -z "$1" ]; then
  
  # If the name of the folder was not specified 
  # in the argument 
  # Then the following message will be displaed 
  # to the screen 
  echo "Warning : Please provide the folder name as an argument"
  exit 0
fi

# We need to verify whether the directory name 
# entered by user really exists or not 
# -d flag will be true if the directory name 
# exists
if [ -d "$1" ]; then

    # if directory control will enter
    # creating a variable  filename to hold the 
    # new file name i.e. new_archieve current date 
    # it will end with the extension ".tar.bz2".
    filename="new_archive $(date '+%d-%m-%y').tar"
    
    # Using tar --create option to create the
    # archive and --file to set the new filename
    tar --create --file="$filename" "$1"
    echo "Archive successfully created."
    
    # if the folder name does not exists 
    # we will simply display the following message 
    # to the screen
    else
        echo "WARNING: Directory name doesn't exists: $1"
  
fi

输出:

已成功存档