Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change directory in batch file using variable

Here's the question:

set Pathname = C:\Program Files
cd %Pathname%
pause

The above doesn't change the directory, as I would expect. Can anybody please tell me why?

like image 322
Shunyata Kharg Avatar asked Nov 09 '10 11:11

Shunyata Kharg


People also ask

How do I change directory in a batch file?

Under Windows-10, go to All Apps, Windows System and the open the Command Prompt window. From the command prompt change directory to the batch file directory: cd \Tutorial\batch. Then type the name of the batch file test_conc followed by Enter.

Can you use variables in batch files?

When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9. You can also use the variables %0 through %9 as input for set. If you call a variable value from a batch file, enclose the value with percent signs (%).


1 Answers

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

like image 89
Patrick Cuff Avatar answered Oct 23 '22 09:10

Patrick Cuff