我有一个特定的要求,我需要你的帮助来编写shell脚本。
这是我到目前为止所做的。
#!/bin/bash
source_exist=false
while true
do
echo -n "Enter source path:"
read source
if [ ! -d $source ]
then
echo "$source is not a valid directory!!!"
echo -n "Try Again [Y/N]"
read result
if [ $result = 'Y' -o $result = 'y' ]
then
continue
else
exit 1;
fi
else
source_exist=true
break;
fi
done
echo -n "enter target path:"
read target
if [ source_exist ]
then
mkdir $target
fi
find $source '*.txt' -exec cp -p --parents \{\} $target \;
答案 0 :(得分:0)
这就是我所做的:
首先,我正在复制整个目录结构,而不复制任何文件。
然后我在源文件夹中搜索leaf目录并将它们写入文件leafs.txt
然后我在目标文件夹中搜索leaf目录并将它们写入另一个文件leafd.txt
由于两个目录结构都相同,因此两个文本文件中的输出相同,只是更改起始目录的名称。
然后我逐行同时读取这两个文件,并将文本文件从源路径行从leafs.txt复制到leafd.txt的目标路径行。
源目录名由用户提供,目标目录由脚本创建,名称为系统日期。
最后删除了临时文件leafs.txt和leafd.txt。
还会生成一个日志,其名称为系统日期,显示哪些文件从哪个源目录复制到目标目录,保留权限,时间戳等。
以下是代码:
1 #!/bin/bash
2
3 source_exist=false
4
5 while true
6 do
7 #Read source path
8 echo -n "Enter source path:"
9 read -r source
10
11 #If source is not a Direcotry
12 if [ ! -d "$source" ]
13 then
14 echo "$source is not a valid directory!!!"
15 echo -n "Try Again [Y/N]"
16 read -r result
17 if [ $result = "Y" -o $result = "y" ]
18 then
19 continue
20 else
21 exit 1;
22 fi
23 else
24 source_exist=true
25 break;
26 fi
27 done
28
29 target=$(date +%F)
30 touch $target.txt
31
32 if [ source_exist ]
33 then
34 #create target directory
35 mkdir -p $target
36 fi
37 #copy source direcotry structure only to the target
38 find $source -type d -printf "$target/%P\0" | xargs -0 mkdir -p
39
40 #find leaf directories in source and write them to a file
41 find $source -depth -type d | while read dir; do [[ ! $prev =~ $dir ]] && echo "${dir}" ; prev="$dir"; done > leafs.txt
42 #find leaf directories in target and write them to a file
43 find $target -depth -type d | while read dir; do [[ ! $prev =~ $dir ]] && echo "${dir}" ; prev="$dir"; done > leafd.txt
44 file1='leafs.txt'
45 file2='leafd.txt'
46 #read both the files simultaneously line by line and copy all .text file from source to destination
47 while IFS= read -r lineA && IFS= read -r lineB <&3;
48 do
49
50 #copy files preserving permission, timestamp etc.
51 cp --preserve -v "$lineA"/*.txt "$lineB" 2>/dev/null >> $target.txt
52
53
54 done <$file1 3<$file2
55 #remove the created text files
56 rm leafs.txt
57 rm leafd.txt
58 exit 0