2017-08-05 89 views
1

我编写了一个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 

回答

1

单引号内是不允许塔变量扩大。

您需要更正这一行:

elif [[ '$2' = '$INDIR' ]]; 

这样:

elif [[ "$2" = "$INDIR" ]]; 
+0

它工作。非常感谢你 –

0

@whoan是正确的对眼前的问题,但我建议的参数解析一个完全重写逻辑使其更简单。对于像-d这样的选项,最好的办法是检查它(/他们),然后从shift的参数列表中删除它们,然后设置位置参数。例如,这意味着INDIR将是$1(如果已设置)或$(pwd);没有它的复杂性有时是$2

此外,最好在shell脚本中使用小写(或混合大小写)变量名称,因为有大量具有特殊含义的全大写变量,并且如果您意外地使用了其中一个...坏东西可以发生。 (经典示例是尝试将$PATH用于搜索命令的目录列表以外的内容,此时您会发现很多“找不到命令”的错误。)另外,最好在所有内容中加上双引号变量引用;有些地方他们没有必要,但是有很多地方可能会造成奇怪的错误。最后,如果未设置变量,则使用备用字符串的外壳快捷方式为:indir="${1:-$(pwd)}"将设置$indir$1(如果设置为非空白),否则将设置为$(pwd)

if [ "$1" = "-d" ]; then 
    debug=true 
    shift # remove -d from the argument list, to simplify parsing the positional parameters 
else 
    debug=false 
fi 

indir="${1:-$(pwd)}" 
outdir="${2:-$indir}"