2016-04-24 78 views
-3

我正在嘗試創建一個腳本,它有點問題。如何編寫一個將一個目錄下的所有文件和目錄複製到另一個目錄的linux腳本?

該腳本應該帶有兩個參數,它們是源目錄和目標目錄,如果用戶輸入少於2個參數,它應該打印出錯誤消息並退出。此外,這個腳本應該檢查源目錄是否存在,如果不存在,它應該打印出錯誤消息並退出。此外,腳本應該檢查目標目錄是否存在,如果不是,它應該創建該目錄。最後,腳本應該將源目錄中的文件複製到目標目錄。

這是我嘗試迄今:

if (($# < 2)); 
    echo "Error: Too few arguments supplied" 
    exit 1 
if [ -d "src_dir" ] 
then 
    echo "Directory src_dir exists." 
else 
    echo "Error: Directory src_dir does not exist." 
fi 

if [ -d "dst_dir" ] 
then 
    echo "Directory dst_dir exists." 
else 
    mkdir dst_dir 
    cp -r src_dir/* dst_dir 
fi 

任何幫助將非常感激。提前致謝!

+0

你有什麼問題?發生了什麼,你期望發生什麼? –

+0

將代碼粘貼到http://shellcheck.net(在頂部添加一個「she-bang」行,即'#!/ bin/bash')。祝你好運。 – shellter

回答

1

爲了檢查正確數量的參數:Check number of arguments passed to a Bash script

if [ "$#" -ne 2 ]; then 
    echo "Error: Too few arguments supplied" 
    exit 1 
fi 

爲了檢查是否該目錄存在與否:Check if a directory exists in a shell script

if [ ! -d "$1" ]; then 
    echo "Error: Directory $1 does not exist." 
    exit 1 
fi 

負責就第二個參數的DIR:How to use Bash to create a folder if it doesn't already exist?

mkdir -p $2 

最後,只是全部複製:

cp -r $1/* $2/