2015-01-08 67 views
1

我知道一个事实,这将是一件非常简单的事情,我将错过最基本的东西,但我无法理解这一点。在bash循环中增加计数

file=($(find $DIRECTORY -maxdepth 1 -type f)) 
total=$(find $DIRECTORY -type f | wc -l) 
count=0 
while [ "$count" -lt "$total" ] 
do 
for f in "$file"; 
do 
echo -n "Would you like to copy $file? " 
read yn 
case $yn in 
Y | y) 
cp $f $TARGET 
chmod =r $TARGET/$(basename $file) 
count=$((count + 1)) 
    ;; 
N | n) 
    echo "skipping" 
    count=$((count + 1)) 
    ;; 
*) echo "Please enter Y or N" 
    exit 1 
    ;; 
esac 
done 
done 

(抱歉关于格式化)。

基本上它在目前

您输入源文件和目标文件这样做。正常工作

$ ./script.sh ~/work ~/folder 
Created target directory. 
Would you like to copy /home/USER/work/cash.sh? 

那么你要么型y/n

其中任何只给出了同样的答复。

$ ./script.sh ~/work ~/folder 
target directory exists, starting copy 
Would you like to copy /home/USER/work/cash.sh? y 
Would you like to copy /home/USER/work/cash.sh? y 

基本上它复制cash.sh文件,它知道有2个目录中的文件,它只是不跳到下一个文件,并保持在相同的一个,我不知道如何来解决这个问题。

老实说,在过去的几个小时里我一直盯着这看,它让我疯狂,任何事情都会有帮助。提前致谢。

+0

如果要复制目录中的所有文件,则需要在副本中添加-r标志。 -r标志表示recrusive – ryekayo

+0

我需要能够逐一复制它们,并让用户决定是否要跳过一个文件或复制它。这仍然适用? – user3381055

+0

Ahhh对不起,没有它在那种情况下。递归标志只会简单地复制目录中的所有内容。 – ryekayo

回答

0

你想改变:

echo -n "Would you like to copy $file? " 

到:

echo -n "Would you like to copy $f? " 
+1

循环中的'$ f'和'$ file'是同样的东西。 “'$ file”附近的引号可以看到这一点。这也不是问题的答案。 –

+0

其实,他想'读-p“你想复制$ f吗?”yn' –

1

首先,不要使用UPPER_CASE_VAR_NAMES。 Here's why

二,报价全部你的变量,除非你知道具体什么时候你不想。 Here's why

要存储的find结果在一个数组,这样你就不会需要运行find两次:

file=($(find "$directory" -maxdepth 1 -type f)) 
total=${#file[@]} # number of elements in the array 

注意包含空格的任何文件名会被分割成单独的词。假设你的文件名不包含换行符,你可以做

mapfile -t file < <(find "$directory" -maxdepth 1 -type f) 

然后遍历数组了:

for f in "${file[@]}"; do 

另一种技术,使得没有关于在你的文件名中哪些字符假设:

find "$directory" -maxdepth 1 -type f -print0 | while IFS= read -d '' -r filename; do # ...