编写一个 Shell 脚本,将指定目录下的指定类型的文件打成一个压缩包
这里主要会涉及到文件查找find和打包tar命令
这是第一版,里面存在着很大的问题
if ["$#" -ne 3]; then # 这里是运行报错的第1行
echo "用法:$0 <目录> <文件类型> <输出压缩包>"
exit 1
fi
dir=$1
file_type=$2
compose_file_path=$3
# 检查文件夹是否存在
if [! -d "$dir" ]; then # 这里是运行报错的第11行
echo "error:目录:'$dir'不存在."
exit 1
fi
# 符合要求的文件是否大于等于1个
target_files=$(find "$dir" -type f -name "$file_type")
if [ -z "$target_files"]; then # 这里是运行报错的第17行
echo "error:没有找到:'$filee_type'对应类型的文件."
exit 1
fi
# 打包符合要求的文件
tar -czvf "$compose_file_path" "$target_files"
echo "打包成功."
我们来看看运行报错
root@hcss-ecs-c2b8:/var/test# vim compose_file.sh
root@hcss-ecs-c2b8:/var/test# chmod +x compose_file.sh
# 这里我们要做的是将 ./目录下的以".sh"结尾类型的文件进行打包放在test.tar.gz中
root@hcss-ecs-c2b8:/var/test# ./compose_file.sh ./ "*.sh" test.tar.gz
./compose_file.sh: line 1: [3: command not found
./compose_file.sh: line 11: [!: command not found
./compose_file.sh: line 17: [: missing `]' # 这三个个相同的报错是因为没有在中括号和条件之间空一格导致的
tar: ./compose_file.sh\n./dir1/param_trans.sh\n./dir1/hello.sh\n./dir1/helloworld.sh\n./file_move.sh: Cannot stat: No such file or directory # 这个报错是因为 在最后打包命令使用时,$target_files 需要没有引号,以便传递多个文件名,否则会将其识别为一个文件,这当然就找不到对应文件和目了
tar: Exiting with failure status due to previous errors
打包成功.
这里是修改后的脚本
if [ "$#" -ne 3 ]; then
echo "用法:$0 <目录> <文件类型> <输出压缩包>"
exit 1
fi
dir=$1
file_type=$2
compose_file_path=$3
# 检查文件夹是否存在
if [ ! -d "$dir" ]; then
echo "error:目录:'$dir'不存在."
exit 1
fi
# 符合要求的文件是否大于等于1个
target_files=$(find "$dir" -type f -name "$file_type")
if [ -z "$target_files" ]; then
echo "error:没有找到:'$filee_type'对应类型的文件."
exit 1
fi
# 打包符合要求的文件
tar -czvf "$compose_file_path" $target_files
echo "打包成功."
以及运行结果
root@hcss-ecs-c2b8:/var/test# ./compose_file.sh ./ "*.sh" test.tar.gz
./compose_file.sh: line 1: [3: command not found
./compose_file.sh
./dir1/param_trans.sh
./dir1/hello.sh
./dir1/helloworld.sh
./file_move.sh
打包成功.
root@hcss-ecs-c2b8:/var/test# ll
total 24
drwxr-xr-x 3 root root 4096 Sep 23 23:14 ./
drwxr-xr-x 14 root root 4096 Sep 21 08:28 ../
-rwxr-xr-x 1 root root 549 Sep 23 23:02 compose_file.sh*
drwxr-xr-x 2 root root 4096 Sep 22 10:07 dir1/
-rwxr-xr-x 1 root root 473 Sep 22 10:07 file_move.sh*
# 这个就是打包后产生的文件
-rw-r--r-- 1 root root 931 Sep 23 23:13 test.tar.gz
root@hcss-ecs-c2b8:/var/test# ./compose_file.sh /var/test "*.sh" test.tar.gz
# 当我们使用绝对路径时这里会有一个提示
tar: Removing leading `/' from member names
/var/test/compose_file.sh
tar: Removing leading `/' from hard link targets
/var/test/dir1/param_trans.sh
/var/test/dir1/hello.sh
/var/test/dir1/helloworld.sh
/var/test/file_move.sh
打包成功.
当使用 tar 命令创建归档时,如果看到 tar: Removing leading ‘/’ from hard link targets 的消息,表示你在归档中使用了绝对路径。tar 会自动去掉绝对路径的前导斜杠,以便在解压时能够保持相对路径。