Bash Shell 遞迴實現目錄中檔案拷貝

來源:互聯網
上載者:User
前言     今天工作中遇到了一個問題,如果將目錄A中的檔案拷貝到目錄B中(前提目錄B沒有該檔案),並保持檔案在目錄A的結構。項目重點如下: 需要在目錄B中保持檔案在目錄A中的結構。假設A目錄檔案 A/test/1.txt,轉移到目錄B中應該是B/test/1.txt。同時還需要考慮目錄B中是否存在test目錄,多級目錄就要考慮遞迴了。(還好,bash shell裡寫個目錄遞迴遍曆還是比較簡單的。) 需要考慮A中檔案是否在B中已經存在同名檔案,如果存在,則不需要拷貝。     項目需求樣本圖如下:

實現     項目需求有了,知道設計到遞迴,代碼就很好寫了。這裡給出一個demo樣本,供大家參考。
#!/bin/bashfunction recursive_copy_file(){    dirlist=$(ls $1)    for name in ${dirlist[*]}    do        if [ -f $1/$name ]; then            # 如果是檔案,並且$2不存在該檔案,則直接copy            if [ ! -f $2/$name ]; then                cp $1/$name $2/$name            fi        elif [ -d $1/$name ]; then            # 如果是目錄,並且$2不存在該目錄,則先建立目錄            if [ ! -d $2/$name ]; then                mkdir -p $2/$name            fi            # 遞迴拷貝            recursive_copy_file $1/$name $2/$name        fi    done}source_dir="/tmp/test/system"dest_dir="/tmp/test/systemback"recursive_copy_file $source_dir $dest_dir

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.