首页 > 解决方案 > 使用读取的输出作为变量时的语法错误

问题描述

我是 bash 的新手,但我必须编写一个简单的脚本来存档:

ARCHIVE_FOLDER=".archive/"
TO_ARCHIVE="folders.txt"
TO_IGNORE="ignore.txt"

mkdir -p $ARCHIVE_FOLDER

while read t_arc; do
    EXCLUDE_STRING=" "
    while read ig_l; do
        while read found_exc; do
            EXCLUDE_STRING="${EXCLUDE_STRING} --exclude ${found_exc}"
        done < find $t_arc -name $ig_l
    done < TO_IGNORE
    tar -czf "${ARCHVE_FOLDER}/${t_arc}.tar.gz"
done < TO_ARCHIVE

它看起来很简单,但是在使用“while read”构造中定义的变量时出现语法错误:

./archive.sh: line 12: syntax error near unexpected token `${t_arc}'
./archive.sh: line 12: `        done < find ${t_arc} -name ${ig_l}'

显然,我什至无法打印它们:

while read t_arc; do
    EXCLUDE_STRING=" "
    printf "%s\n" $t_arc # prints noting

我在这里做错了什么?

标签: bash

解决方案


后面的符号<只是一个文件名。如果要使用进程替换,则其语法为

done < <(find ...)

或者,您可以运行

find ... |
while read -r ...

(可能还会将您的其他read语句更改为read -r,除非您特别需要在输入中围绕反斜杠的奇怪的遗留 POSIX 行为read。)


推荐阅读