Linux Shell: copy a folder script

Source: Internet
Author: User

Write a script to copy the folder.

Principle: first package the folder to be copied with tar, then copy the package, and then unpack the package.
Receive two parameters. If the parameter is smaller than 2, an error is returned.
If the target folder is not a folder, an error is returned.
If the source file (folder) does not exist, an error is returned.
Then extract the file to be copied, such as/home/user1/test,
Then, package the file (folder) in tar.
Upload the package to the target folder, decompress the package, and delete the intermediate file (generated by TAR.


 

Code :#! /Bin/sh
# Cpdir source_dir target_dir
# Author hjack
# Date: 2006.3.25
# Copy dir

######### Variables define ##########
Source_dir = $1
Target_dir = $2
Current_dir = 'pwd'
Source_file = ""

######### Main start here ###########
# Check the argements.
If [$ #-lt 2]; then
Echo "request more arguments ."
Exit
Fi

# Does the target dir exist?
If [! -D $ target_dir]; then
Echo "not such dir ."
Exit
Fi

If [-e $ source_dir]; then
# Sourcedir string ends '/'.
Echo $ source_dir | grep/$>/dev/null
If [$? -EQ 0]; then
# Get the file or dir name. eg:/home/user1/test, it will get test.
Source_file = $ (echo $ source_dir | awk-F/'{print $(NF-1 )}')
Else
Source_file = $ (echo $ source_dir | awk-F/'{print $ NF }')
Fi
Else
Echo "not such dir ."
Exit
Fi

# First, compress the Dir.
Tempfile = "tmp. cpdir0000123456789". $ source_file ". tgz"
Tar zcf $ tempfile $ source_file

# Then, decompress the tar file.
MV $ tempfile $ target_dir
CD $ target_dir
Tar zxf $ tempfile
Rm $ tempfile
CD $ current_dir
Echo "Copy finished ."

Note:
$ # Indicates the number of command parameters.
[-D $ target_dir] test whether the target folder is a folder.
[$? -EQ 0] test whether the previous command is successfully executed.
$? Is the return code of the previous command.
Tar packaging command.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.