Sean
Sean

Reputation: 13

How to set variable in one bat file and send to another?

I have two bat files, program 1 is working so when the user enters a "file name" it will open the file and edit it. However, I would also like to make it so if program 2 opened and the username just enters a file name it will send that variable over to program 1 which then uses the variable to edit the file instead of asking for a user to input the file name.

I tried creating a variable on program 2 and then using %1 but don't know how to go forward from here.

Program 1:

set /p FileName=
If exist %cd%\%FileName% start %FileName%

Program 2:

@echo off
set /p FileName=[FileName]: 
call editor.bat %FileName%

I would like program 1 to check if program 2 has sent a variable if not to continue as normal

Upvotes: 1

Views: 207

Answers (1)

Joe6.626070
Joe6.626070

Reputation: 319

To pass a variable, you would need to use it as an argument:

bat1.bat

@echo off
set /p filename="Enter Filename: "
bat2 %filename%

bat2.bat

@echo off
echo %1

Both files need to be in the same directory otherwise you must use absolute path when calling bat2.bat

%1 is the first argument, you can use multiple argument i.e. %2, %3

Further reading: http://www.pcstats.com/articleview.cfm?articleID=1767

Example scripts: https://www.instructables.com/id/5-Cool-Batch-Files/

EDIT

This if from: Batch parse each parameter

The SHIFT command shifts the arguments to the left until there aren't anymore. So after %1 is called, %2 becomes %1, etc

@ECHO OFF
:Loop
IF "%1"=="" GOTO Continue
   ECHO %1
SHIFT
GOTO Loop
:Continue

Upvotes: 1

Related Questions