mrcoulson
mrcoulson

Reputation: 1403

Renaming file in bash script breaks the script

Good day! I have the following script which is supposed to rename and then send files in a folder on my Mac to an FTP server.

for f in "$@"
    do
        mv "$f" "${f%.mpeg}.mpg"
        curl -T "$f" ftp://1.2.3.4/Vol123456-01/MPEG/ --user me:secret
        mv "$f" "/Users/me/Sent Stuff"
    done

That works fine except for that first mv line. The script successfully renames the file, but then the following commands seem to no longer be able to find "$f". I am pretty new to bash scripting. Is there a way to refresh perhaps what "$f" means so that the curl and mv lines know what it is? Thanks in advance!

Upvotes: 0

Views: 86

Answers (2)

claj
claj

Reputation: 5402

You could store the new name in another variable and then use that when you want to reach the file.

newname="${f%.mpeg}.mpg"

and then use the "$newname" for getting the variable.

Upvotes: 3

Mad Physicist
Mad Physicist

Reputation: 114230

You have nailed the problem exactly. The first mv renames the file. The original name "$f" no longer exists. Try this:

for f in "$@"
do
    g="${f%.mpeg}.mpg"
    mv "$f" "$g"
    curl -T "$g" ftp://1.2.3.4/Vol123456-01/MPEG/ --user me:secret
    mv "$g" "/Users/me/Sent Stuff"
done

Upvotes: 5

Related Questions