我编写了一个Bash脚本,用于将目录的内容备份到.tar
文件中。我打算将脚本更新为更具组织性,可移植性和可共享的内容。然而,我不能在我的生活中理解我的代码中的错误,在这种情况下,输出不应将$OUTDIR
更改为与$INDIR
相同的路径。使用bash脚本备份目录的奇怪输出
只要将-d
附加到文件命令的参数(它应该显示脚本的实际要点中使用的字符串tar
命令)来定义它自己的参数,就会发生这种情况。我已经将我的代码的一部分重写了两次,我不明白为什么输出每次都会有所不同。
#!/bin/bash
# Script will only back up an accessible directories
# Any directories that require 'sudo' will not work.
if [[ -z $1 ]]; then # This specifically
INDIR=$(pwd); debug=false; # is the part where
elif [[ $1 == '-d' ]]; then # the 'debug' variable
debug=true; # is tampering with
if [[ -z $2 ]]; then INDIR=$(pwd); # the output somehow.
else INDIR=$2; fi
else
INDIR=$1; debug=false; fi
if [[ -z $2 ]]; then
OUTDIR=$INDIR
elif [[ '$2' = '$INDIR' ]]; then
if [[ -z $3 ]]; then OUTDIR=$INDIR;
else OUTDIR=$3; fi
else
OUTDIR=$2; fi
FILENAME=bak_$(date +%Y%m%d_%H%M).tar
FILEPATH=$OUTDIR'/'$FILENAME
LOGPATH=$OUTDIR'/bak.log'
if [[ "$debug" = true ]]; then
echo "Input directory: "$INDIR
echo "Output directory: "$OUTDIR
echo "Output file path: "$FILEPATH
echo "Log file path: "$LOGPATH
else
tar --exclude=$FILEPATH --exclude=$LOGPATH \
-zcvf $FILEPATH $INDIR > $LOGPATH
fi
这是输出
[email protected]:~$ bakdir -d
Input directory: /home/gnomop
Output directory: /home/gnomop
Output file path: /home/gnomop/bak_20170804_2123.tar
Log file path: /home/gnomop/bak.log
[email protected]:~$ bakdir -d /home/other
Input directory: /home/other
Output directory: /home/other
Output file path: /home/other/bak_20170804_2124.tar
Log file path: /home/other/bak.log
[email protected]:~$ bakdir -d /home/other /home/other/bak
Input directory: /home/other
Output directory: /home/other
Output file path: /home/other/bak_20170804_2124.tar
Log file path: /home/other/bak.log
它工作。非常感谢你 –