简体   繁体   中英

Variables misbehave in command prompt Windows 10

I have a question about variables in Windows cmd. The task: Run through all directories in the same folder as main script, search for a files with specific name, enter those directories, run those files, return to original folder.

The main script is:

SET origin=%~dp0
Echo "%origin%"
cd "%origin%"

for /R .\ %%a IN (*file_to_run_name.cmd) do (
    echo "%%a"
    echo "%%~da%%~pa"
    cd "%%~da%%~pa"
    %%a )

Echo "%origin%"
cd "%origin%"

This script does, what I need except of one thing: it does not change the working directory to the original one. To be more precise, the last fragment:

Echo "%origin%"
cd "%origin%"

is not even called.

How to fix that? Thanks.

It is not the variables that misbehave. You are trying to run other batch scripts ( .cmd ), and execution control does not return to the main script unless you use call . In addition, use cd /D rather than just /D , because if the target directory is on another drive, /D must be used. And the string %%~da%%~pa can be simplified to %%~dpa . Finally, let me recommend to use the quoted set syntax to protect special characters.

So here is the fixed code:

set "origin=%~dp0"
echo "%origin%"
cd /D "%origin%"

for /R .\ %%a in (*file_to_run_name.cmd) do (
    echo "%%a"
    echo "%%~dpa"
    cd /D "%%~dpa"
    call "%%a"
)

echo "%origin%"
cd /D "%origin%"

However, this can still be improved: There are the commands pushd (to store the current directory and then to change to a specified one) and popd (to restore the previously stored directory), so you do not need to store the original path to a variable.

This is how to apply them:

echo "%~dp0"
cd /D "%~dp0"

for /R .\ %%a in (*file_to_run_name.cmd) do (
    echo "%%a"
    echo "%%~dpa"
    pushd "%%~dpa"
    call "%%a"
    popd
)

echo "%CD%"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM