2013-04-13 47 views
1
# define some variables for later 
date=`date` 
usr=`whoami` 

# define usage function to echo syntax if no args given 
usage(){ 
    echo "error: filename not specified" 
    echo "Usage: $0 filename directory/ directory/ directory/" 
    exit 1 
} 

# define copyall function 
copyall() { 
    # local variable to take the first argument as file 
    local file="$1" dir 
    # shift to the next argument(s) 
    shift 

    # loop through the next argument(s) and copy $file to them 
    for dir in "[email protected]"; do 
     cp -R "$file" "$dir" 
    done 
} 

# function to check if filename exists 
# $f -> store argument passed to the script 
file_exists(){ 
    local f="$1" 
    [[ -f "$f" ]] && return 0 || return 1 
} 
# call usage() function to print out syntax 
[[ $# -eq 0 ]] && usage 

這裏就是我想不通似乎無法得到這個功能使用bash工作

# call file_exists() and copyall() to do the dirty work 
if (file_exists "$1") then 
    copyall 

我也很想找出如何藉此在下一個回波部分,它凝結到一行。而不是1美元,然後轉移然後繼續前進。也許分裂成一個數組?

echo "copyall: File $1 was copied to" 
    shift 
    echo "[email protected] on $date by $usr" 
else 
    echo "Filename not found" 
fi 

exit 0 
+0

你可以放棄&& return 0 ||返回1';在函數的最後一行是'[[-f「$ f」]]'時,如果文件存在則返回0,否則返回1。 – chepner

回答

0

您可能只需要刪除括號周圍file_exists "$1",並添加一個分號:

if file_exists "$1"; then 
    copyall 
+0

只是固定的格式;也許現在會更容易閱讀。我也嘗試刪除()的,但仍然沒有去。 – hdub

+0

所以,如果它不起作用,*會發生什麼? – lxop

+0

它只是回聲文件被複制,但copyall函數甚至沒有被稱爲似乎。沒有錯誤或任何東西。即使在copyall函數中有回聲,甚至不會顯示。 – hdub

1

在我看來,該file_exists宏是多餘的:

if [ -f "$1" ] 
then copy_all "[email protected]" 
else echo "$0: no such file as $1" >&2; exit 1 
fi 

甚至只是:

[ -f "$1" ] && copy_all "[email protected]"