acidblue
acidblue

Reputation: 1

Variables in Batch FTP script

In C you can use %username% as a variable for the current user's name for directory listings and such: c:\documents and settings\%username%\

Is there something like this for a batch script? Using just %username% doesn't seem to help.

I wrote a script that accesses my FTP server so I can load files to the server. I want my friends to be able to use this script, but I don't want to have to write several different scripts. Here is what I have so far:

@echo off
@ftp -s:"%~f0" &GOTO: EOF
open FTP.server.com
user
pass
cd /home/ftp
bin
lcd "c:\documents and settings\%username%\my documents\FTP"
mput *txt
pause
bye

There's gotta be a way

Upvotes: 0

Views: 3834

Answers (3)

Mike Caron
Mike Caron

Reputation: 14561

Instead of using lcd, a better idea might be to change the working directory in the outer batch file.

@echo off

@pushd "c:\documents and settings\%username%\my documents\FTP"

@ftp -s:"%~f0" &GOTO: EOF

open FTP.server.com
user
pass
cd /home/ftp
bin
mput *txt

@pause

The only problem with this solution, is that the script itself is no longer in the working directory, and so you need to add a path for that. (Or, put it in the FTP folder ;)

Also, minor pedantry, but this is not actually a correct way to find My documents. In particular, on Vista or Windows 7, User profiles are stored in C:\Users. And, it's possible for users to move My Documents (on my computer, My Documents is located in D:\Mike's Documents)

However, there doesn't appear to be an environment variable that points directly at My Documents, so you will have to make do with this:

"%userprofile%\my documents\FTP"

If the people running this script are running XP and haven't moved their My Documents, then this doesn't really matter.

Upvotes: 0

poke
poke

Reputation: 2982

This can be done if you change the batch file so that it creates a script file every time the batch file runs. You can do this by using the echo command to write the script lines to script file, which you can then pass to the ftp command. The reason this works is that echo will expand the %username% variable before writing it to the script file:

@echo off
del script.txt
echo open FTP.server.com>>script.txt
.
[echo rest of script lines to file]
.
echo lcd "c:\documents and settings\%username%\my documents\FTP">>script.txt
echo echo mput *txt>>script.txt

@ftp -s:script.txt

Upvotes: 1

acidblue
acidblue

Reputation: 1

I believe i found a better way, although it's a bit more code.

set "rootdir=%userprofile%\my documents"

set "destdir=c:\
for /f "delims=" %%a in ('dir /b /s "%rootdir%*.txt"') do copy "%%~a" "%destdir%"

And then the usual FTP stuff, including lcd c:\

Ive tested this and it works, although I would like to find a simpler way. I tried using xcopy but for some reason it doesn't work on my system, the cmd screen just hangs. Also tried just using copy, but that gave me "can't find file" errors.

Upvotes: 0

Related Questions