Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file from batch file's directory

I know only the very basics of writing batch files. I am trying to figure out how to write one that, given any directory it is in, would copy a file that is within the same directory and put it in a new location. I know how to copy the file and move it, but I don't know how to write the batch file to understand its directory and then grab a different file.

I read that %0 represents the directory the file is in, but then how can I append a file to that?

I've tried this:

copy "%0\Move.txt" "C:\"

Maybe that was stupid but I'm a newbie. Help please?

like image 247
Kyle Wright Avatar asked Oct 10 '13 18:10

Kyle Wright


2 Answers

%0 contains the full path and file name to the batch script.

Use just %~dp0 to get the path without the batch script file name.

copy "%~dp0\Move.txt" "C:\"

Use the echo command to view what a variable holds when you are having a problem.

echo %0

From call /?

Substitution of batch parameters (%n) has been enhanced.  You can
now use the following optional syntax:

    %~1         - expands %1 removing any surrounding quotes (")
    %~f1        - expands %1 to a fully qualified path name
    %~d1        - expands %1 to a drive letter only
    %~p1        - expands %1 to a path only
    %~n1        - expands %1 to a file name only
    %~x1        - expands %1 to a file extension only
    %~s1        - expanded path contains short names only
    %~a1        - expands %1 to file attributes
    %~t1        - expands %1 to date/time of file
    %~z1        - expands %1 to size of file
    %~$PATH:1   - searches the directories listed in the PATH
                   environment variable and expands %1 to the fully
                   qualified name of the first one found.  If the
                   environment variable name is not defined or the
                   file is not found by the search, then this
                   modifier expands to the empty string

The modifiers can be combined to get compound results:

    %~dp1       - expands %1 to a drive letter and path only
    %~nx1       - expands %1 to a file name and extension only
    %~dp$PATH:1 - searches the directories listed in the PATH
                   environment variable for %1 and expands to the
                   drive letter and path of the first one found.
    %~ftza1     - expands %1 to a DIR like output line

In the above examples %1 and PATH can be replaced by other
valid values.  The %~ syntax is terminated by a valid argument
number.  The %~ modifiers may not be used with %*
like image 77
David Ruhmann Avatar answered Nov 03 '22 20:11

David Ruhmann


If you are just trying to copy a file from the current directory to a new one, you may simply do this:

copy "Move.txt" "C:\"

Not prefixing the file "Move.txt" means it is in the current directory.

like image 33
gh123man Avatar answered Nov 03 '22 20:11

gh123man