如何阻止bash for循环执行空列表

时间:2018-06-06 01:58:17

标签: bash

我使用简单的bash脚本从FTP服务器读取文件,转换为dos格式,然后移动到另一个文件夹:

#!/bin/bash

SOURCE="$1"
DESTINATION="$2"

# Use globbing to grab list of files
for x in $1/*.txt; do
 f=$(basename $x)
 todos $x
 echo "Moving $x to $DESTINATION/$f"
 mv $x $DESTINATION/$f
done

一个非常简单的问题 - 如果没有要移动的txt文件,如何停止循环执行?

1 个答案:

答案 0 :(得分:4)

bash shell有nullglob shell选项,导致无法匹配的shell globs扩展为空:

#!/bin/bash

source=$1
target=$2

shopt -s nullglob

for name in "$source"/*.txt; do
    todos "$name"

    dest="$target/${name##*/}"
    printf 'Moving %s to %s' "$name" "$dest"
    mv -- "$name" "$dest"
done

我也冒昧地修改你的代码,这样即使给定的目录名中包含空格,换行符或shell globs,或者以破折号开头的名称,它也能正常工作。

相关: