1

I am using a simple bash script to read files from an FTP server, convert to dos format and then move to another folder:

#!/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

A really simple question - how do I stop the loop executing when there are no txt files to be moved?

skyman
  • 2,255
  • 4
  • 32
  • 55

1 Answers1

4

The bash shell has a nullglob shell option which causes unmatched shell globs to expand to nothing:

#!/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

I've also taken the liberty to fix your code so that it work even if given directory names with spaces, newlines, or shell globs in them, or names that start with dashes.

Related:

Kusalananda
  • 14,885
  • 3
  • 41
  • 52