在某些情况下,Dash变量扩展不起作用

时间:2013-01-31 12:16:31

标签: shell scripting dash-shell

这项工作正在测试虚拟机器上完成

在我的/ root目录中,我创建了以下内容:
“/根/ foo” 的
“/根/栏”
“/ root /我有多个单词”

这是我目前拥有的(相关)代码

  if [ ! -z "$BACKUP_EXCLUDE_LIST" ]
  then
    TEMPIFS=$IFS
    IFS=:
    for dir in $BACKUP_EXCLUDE_LIST
    do
      if [ -e "$3/$dir" ] # $3 is the backup source
      then
          BACKUP_EXCLUDE_PARAMS="$BACKUP_EXCLUDE_PARAMS --exclude='$dir'"
      fi    
    done
    IFS=$TEMPIFS
  fi


  tar $BACKUP_EXCLUDE_PARAMS -cpzf  $BACKUP_PATH/$BACKUP_BASENAME.tar.gz -C $BACKUP_SOURCE_DIR $BACKUP_SOURCE_TARGET

当我使用sh -x

运行脚本时会发生这种情况
+ IFS=:
+ [ -e /root/foo ]
+ BACKUP_EXCLUDE_PARAMS= --exclude='foo'
+ [ -e /root/bar ]
+ BACKUP_EXCLUDE_PARAMS= --exclude='foo' --exclude='bar'
+ [ -e /root/i have multiple words ]
+ BACKUP_EXCLUDE_PARAMS= --exclude='foo' --exclude='bar' --exclude='i have multiple words'
+ IFS=  

# So far so good

+ tar --exclude='foo' --exclude='bar' --exclude='i have multiple words' -cpzf /backup/root/daily/root_20130131.071056.tar.gz -C / root
tar: have: Cannot stat: No such file or directory
tar: multiple: Cannot stat: No such file or directory
tar: words': Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

# WHY? :(

支票成功完成,但--exclude='i have multiple words'不起作用。

请注意,当我在我的shell中手动输入它时它会起作用:

tar --exclude='i have multiple words' -cf /somefile.tar.gz /root

我知道这在使用数组时会在bash中起作用,但我希望这是POSIX。

有解决方法吗?

2 个答案:

答案 0 :(得分:1)

考虑这个脚本; ('with whitespace'和'example.desktop'是示例文件)

#!/bin/bash

arr=("with whitespace" "examples.desktop")

for file in ${arr[@]}
do
    ls $file
done

这与你的完全一样输出;

21:06 ~ $ bash test.sh 
 ls: cannot access with: No such file or directory
 ls: cannot access whitespace: No such file or directory
 examples.desktop

您可以将IFS设置为'\ n'字符以转义文件名上的空格。

#!/bin/bash

arr=("with whitespace" "examples.desktop")

(IFS=$'\n';
    for file in ${arr[@]}
    do
        ls $file
    done
)

第二个版本的输出应为;

21:06 ~ $ bash test.sh 
 with whitespace
 examples.desktop

答案 1 :(得分:0)

David the H. from the LinuxQuestions forums steered me in the right direction.

首先,在我的问题中,我没有使用IFS =:一直到tar命令 其次,我包括" set -f"为了安全

BACKUP_EXCLUDE_LIST="foo:bar:i have multiple words"

# Grouping our parameters
if [ ! -z "$BACKUP_EXCLUDE_LIST" ]
then
  IFS=:         # Here we set our temp $IFS
  set -f        # Disable globbing
  for dir in $BACKUP_EXCLUDE_LIST
  do
    if [ -e "$3/$dir" ]  # $3 is the directory that contains the directories defined in $BACKUP_EXCLUDE_LIST
    then
      BACKUP_EXCLUDE_PARAMS="$BACKUP_EXCLUDE_PARAMS:--exclude=$dir"
    fi    
  done
fi

# We are ready to tar

tar $BACKUP_EXCLUDE_PARAMS \
  -cpzf  "$BACKUP_PATH/$BACKUP_BASENAME.tar.gz" \
  -C "$BACKUP_SOURCE_DIR" \
  "$BACKUP_SOURCE_TARGET"
unset IFS       # our custom IFS has done it's job. Let's unset it!
set +f          # Globbing is back on

我建议不要像我一样使用TEMPIFS变量,因为该方法没有正确设置IFS。完成后,最好取消设置IFS