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?

1

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.