DarkVeneno
DarkVeneno

Reputation: 99

Create file inside folder without using cd to open folder

I'm creating a script that creates a file inside the current directory.

@echo off
set /p file= filename and extension: 
echo something_test >> %file%

But, let's say the current directory is this:

INSIDE (fo) main_folder: {
    (fi) script.bat
    (fo) somefolder
}

(fi = file and fo = folder; script.bat is the script I'm making)

If I run the script and input file.txt, (fi) file.txt will be created in (fi) script.bat's main directory ((fo) main_folder).

Now let's say I want to create it inside (fo) somefolder.

The obvious thing would be to do this:

@echo off
cd somefolder
set /p file= filename and extension: 
echo something_test >> %file%

Then; If I run the script and input file.txt, (fi) file.txt will be created in (fi) script.bat's WORKING directory ((fo) somefolder).

But what I want to do is to, just by inputing into the set /p command, create the file in (fo) somefolder, without using the cd command.

And how to, just by inputing into the set /p command, create the file in (fo) main_folder's main directory, without using the cd.. command?

Upvotes: 0

Views: 573

Answers (1)

T3RR0R
T3RR0R

Reputation: 2951

In your Main Script, prior to calling any functions, Use:

Set "Prog_Dir=%~dp0"

REM %~dp0 Expands to the directory which the Batch is run in - The folder it's in.

Set "somefolder=%Prog_Dir%somefolder"

To create a file In your Scripts Dir:

(
ECHO Your text
) >"%Prog_Dir%\filename.ext"

To create a file In your Scripts Sub Dir:

(
ECHO Your text
) >"%somefolder%\filename.ext"

This approach of using relative pathways ensures the script will function as intended irregardless of where the scripts folder is located.

In order to use set /p to adjust the directory, use it to test a value. EG:

Set \p StoreLocation=[1: MainDirectory 2:SomeFolder]
IF %StoreLocation%==1 Set "SaveLoc=%Prog_Dir%"

IF %StoreLocation%==2 Set "SaveLoc=%somefolder%\"

And change your store method to:

(
ECHO Your text
) >"%SaveLoc%filename.ext"

I would however recommend using choice within a callable function to change the value over using set /p.

Upvotes: 1

Related Questions