I'm trying to generate a war file in play application.
I am using starter java project: play-java-starter-example. Play version 2.6.2 in Windows.
I added the plugin play2war in project/plugins.sbt:
addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.4.0")
After that I ran the following commands:
C:\project_name>sbt
[project_name]$ dist
It generates a zip file as it's supposed to.
The next step according to the official Doc is to execute a .bat file inside target/universal/[project_name]/bin
Im stuck at this step, execution of the script gives the following message:
console output
Here is the content of the .bat file generated by the dist command:
#REM play-java-starter-example launcher script
#REM
#REM Environment:
#REM JAVA_HOME - location of a JDK home dir (optional if java on path)
#REM CFG_OPTS - JVM options (optional)
#REM Configuration:
#REM PLAY_JAVA_STARTER_EXAMPLE_config.txt found in the PLAY_JAVA_STARTER_EXAMPLE_HOME.
#setlocal enabledelayedexpansion
#echo off
if "%PLAY_JAVA_STARTER_EXAMPLE_HOME%"=="" set "PLAY_JAVA_STARTER_EXAMPLE_HOME=%~dp0\\.."
set "APP_LIB_DIR=%PLAY_JAVA_STARTER_EXAMPLE_HOME%\lib\"
rem Detect if we were double clicked, although theoretically A user could
rem manually run cmd /c
for %%x in (!cmdcmdline!) do if %%~x==/c set DOUBLECLICKED=1
rem FIRST we load the config file of extra options.
set "CFG_FILE=%PLAY_JAVA_STARTER_EXAMPLE_HOME%\PLAY_JAVA_STARTER_EXAMPLE_config.txt"
set CFG_OPTS=
if exist "%CFG_FILE%" (
FOR /F "tokens=* eol=# usebackq delims=" %%i IN ("%CFG_FILE%") DO (
set DO_NOT_REUSE_ME=%%i
rem ZOMG (Part #2) WE use !! here to delay the expansion of
rem CFG_OPTS, otherwise it remains "" for this loop.
set CFG_OPTS=!CFG_OPTS! !DO_NOT_REUSE_ME!
)
)
rem We use the value of the JAVACMD environment variable if defined
set _JAVACMD=%JAVACMD%
if "%_JAVACMD%"=="" (
if not "%JAVA_HOME%"=="" (
if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"
)
)
if "%_JAVACMD%"=="" set _JAVACMD=java
rem Detect if this java is ok to use.
for /F %%j in ('"%_JAVACMD%" -version 2^>^&1') do (
if %%~j==java set JAVAINSTALLED=1
if %%~j==openjdk set JAVAINSTALLED=1
)
rem BAT has no logical or, so we do it OLD SCHOOL! Oppan Redmond Style
set JAVAOK=true
if not defined JAVAINSTALLED set JAVAOK=false
if "%JAVAOK%"=="false" (
echo.
echo A Java JDK is not installed or can't be found.
if not "%JAVA_HOME%"=="" (
echo JAVA_HOME = "%JAVA_HOME%"
)
echo.
echo Please go to
echo http://www.oracle.com/technetwork/java/javase/downloads/index.html
echo and download a valid Java JDK and install before running play-java-starter-example.
echo.
echo If you think this message is in error, please check
echo your environment variables to see if "java.exe" and "javac.exe" are
echo available via JAVA_HOME or PATH.
echo.
if defined DOUBLECLICKED pause
exit /B 1
)
rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config.
set _JAVA_OPTS=%JAVA_OPTS%
if "!_JAVA_OPTS!"=="" set _JAVA_OPTS=!CFG_OPTS!
rem We keep in _JAVA_PARAMS all -J-prefixed and -D-prefixed arguments
rem "-J" is stripped, "-D" is left as is, and everything is appended to JAVA_OPTS
set _JAVA_PARAMS=
set _APP_ARGS=
:param_loop
call set _PARAM1=%%1
set "_TEST_PARAM=%~1"
if ["!_PARAM1!"]==[""] goto param_afterloop
rem ignore arguments that do not start with '-'
if "%_TEST_PARAM:~0,1%"=="-" goto param_java_check
set _APP_ARGS=!_APP_ARGS! !_PARAM1!
shift
goto param_loop
:param_java_check
if "!_TEST_PARAM:~0,2!"=="-J" (
rem strip -J prefix
set _JAVA_PARAMS=!_JAVA_PARAMS! !_TEST_PARAM:~2!
shift
goto param_loop
)
if "!_TEST_PARAM:~0,2!"=="-D" (
rem test if this was double-quoted property "-Dprop=42"
for /F "delims== tokens=1,*" %%G in ("!_TEST_PARAM!") DO (
if not ["%%H"] == [""] (
set _JAVA_PARAMS=!_JAVA_PARAMS! !_PARAM1!
) else if [%2] neq [] (
rem it was a normal property: -Dprop=42 or -Drop="42"
call set _PARAM1=%%1=%%2
set _JAVA_PARAMS=!_JAVA_PARAMS! !_PARAM1!
shift
)
)
) else (
if "!_TEST_PARAM!"=="-main" (
call set CUSTOM_MAIN_CLASS=%%2
shift
) else (
set _APP_ARGS=!_APP_ARGS! !_PARAM1!
)
)
shift
goto param_loop
:param_afterloop
set _JAVA_OPTS=!_JAVA_OPTS! !_JAVA_PARAMS!
:run
set "APP_CLASSPATH=%APP_LIB_DIR%\..\conf\;%APP_LIB_DIR%\play-java-starter-example.play-java-starter-example-1.0-SNAPSHOT-sans-externalized.jar;%APP_LIB_DIR%\org.scala-lang.scala-library-2.12.2.jar;%APP_LIB_DIR%\com.typesafe.play.twirl-api_2.12-1.3.3.jar;%APP_LIB_DIR%\org.scala-lang.modules.scala-xml_2.12-1.0.6.jar;%APP_LIB_DIR%\com.typesafe.play.play-server_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.build-link-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-exceptions-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-netty-utils-2.6.2.jar;%APP_LIB_DIR%\org.slf4j.slf4j-api-1.7.25.jar;%APP_LIB_DIR%\org.slf4j.jul-to-slf4j-1.7.25.jar;%APP_LIB_DIR%\org.slf4j.jcl-over-slf4j-1.7.25.jar;%APP_LIB_DIR%\com.typesafe.play.play-streams_2.12-2.6.2.jar;%APP_LIB_DIR%\org.reactivestreams.reactive-streams-1.0.0.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-stream_2.12-2.5.3.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-actor_2.12-2.5.3.jar;%APP_LIB_DIR%\com.typesafe.config-1.3.1.jar;%APP_LIB_DIR%\org.scala-lang.modules.scala-java8-compat_2.12-0.8.0.jar;%APP_LIB_DIR%\com.typesafe.ssl-config-core_2.12-0.2.1.jar;%APP_LIB_DIR%\org.scala-lang.modules.scala-parser-combinators_2.12-1.0.6.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-slf4j_2.12-2.5.3.jar;%APP_LIB_DIR%\com.fasterxml.jackson.core.jackson-core-2.8.9.jar;%APP_LIB_DIR%\com.fasterxml.jackson.core.jackson-annotations-2.8.9.jar;%APP_LIB_DIR%\com.fasterxml.jackson.core.jackson-databind-2.8.9.jar;%APP_LIB_DIR%\com.fasterxml.jackson.datatype.jackson-datatype-jdk8-2.8.9.jar;%APP_LIB_DIR%\com.fasterxml.jackson.datatype.jackson-datatype-jsr310-2.8.9.jar;%APP_LIB_DIR%\commons-codec.commons-codec-1.10.jar;%APP_LIB_DIR%\com.typesafe.play.play-json_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-functional_2.12-2.6.2.jar;%APP_LIB_DIR%\org.scala-lang.scala-reflect-2.12.2.jar;%APP_LIB_DIR%\org.typelevel.macro-compat_2.12-1.1.1.jar;%APP_LIB_DIR%\joda-time.joda-time-2.9.9.jar;%APP_LIB_DIR%\com.google.guava.guava-22.0.jar;%APP_LIB_DIR%\com.google.code.findbugs.jsr305-1.3.9.jar;%APP_LIB_DIR%\com.google.errorprone.error_prone_annotations-2.0.18.jar;%APP_LIB_DIR%\com.google.j2objc.j2objc-annotations-1.1.jar;%APP_LIB_DIR%\org.codehaus.mojo.animal-sniffer-annotations-1.14.jar;%APP_LIB_DIR%\io.jsonwebtoken.jjwt-0.7.0.jar;%APP_LIB_DIR%\org.apache.commons.commons-lang3-3.6.jar;%APP_LIB_DIR%\javax.transaction.jta-1.1.jar;%APP_LIB_DIR%\javax.inject.javax.inject-1.jar;%APP_LIB_DIR%\com.typesafe.play.play-java-forms_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-java_2.12-2.6.2.jar;%APP_LIB_DIR%\org.reflections.reflections-0.9.11.jar;%APP_LIB_DIR%\org.javassist.javassist-3.21.0-GA.jar;%APP_LIB_DIR%\net.jodah.typetools-0.5.0.jar;%APP_LIB_DIR%\org.hibernate.hibernate-validator-5.4.1.Final.jar;%APP_LIB_DIR%\javax.validation.validation-api-1.1.0.Final.jar;%APP_LIB_DIR%\org.jboss.logging.jboss-logging-3.3.0.Final.jar;%APP_LIB_DIR%\com.fasterxml.classmate-1.3.1.jar;%APP_LIB_DIR%\org.springframework.spring-context-4.3.9.RELEASE.jar;%APP_LIB_DIR%\org.springframework.spring-core-4.3.9.RELEASE.jar;%APP_LIB_DIR%\org.springframework.spring-beans-4.3.9.RELEASE.jar;%APP_LIB_DIR%\com.typesafe.play.filters-helpers_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.play.play-logback_2.12-2.6.2.jar;%APP_LIB_DIR%\ch.qos.logback.logback-classic-1.2.3.jar;%APP_LIB_DIR%\ch.qos.logback.logback-core-1.2.3.jar;%APP_LIB_DIR%\com.typesafe.play.play-akka-http-server_2.12-2.6.2.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-http-core_2.12-10.0.9.jar;%APP_LIB_DIR%\com.typesafe.akka.akka-parsing_2.12-10.0.9.jar;%APP_LIB_DIR%\com.typesafe.play.play-guice_2.12-2.6.2.jar;%APP_LIB_DIR%\com.google.inject.guice-4.1.0.jar;%APP_LIB_DIR%\aopalliance.aopalliance-1.0.jar;%APP_LIB_DIR%\com.google.inject.extensions.guice-assistedinject-4.1.0.jar;%APP_LIB_DIR%\com.h2database.h2-1.4.194.jar;%APP_LIB_DIR%\play-java-starter-example.play-java-starter-example-1.0-SNAPSHOT-assets.jar"
set "APP_MAIN_CLASS=play.core.server.ProdServerStart"
if defined CUSTOM_MAIN_CLASS (
set MAIN_CLASS=!CUSTOM_MAIN_CLASS!
) else (
set MAIN_CLASS=!APP_MAIN_CLASS!
)
rem Call the application and pass all arguments unchanged.
"%_JAVACMD%" !_JAVA_OPTS! !PLAY_JAVA_STARTER_EXAMPLE_OPTS! -cp "%APP_CLASSPATH%" %MAIN_CLASS% !_APP_ARGS!
#endlocal
:end
exit /B %ERRORLEVEL%
I figured it out.
Here are the steps:
I added the plugin play2war in project/plugins.sbt:
addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.4.0")
add in build.sbt
import com.github.play2war.plugin._
libraryDependencies ++= Seq( "com.github.play2war" % "play2-war_2.9.1" % "0.8.2" )
Play2WarPlugin.play2WarSettings
Play2WarKeys.servletVersion := "3.1"
execute command sbt war
Except the war generated is quit strange, it contains only jar files, is it normal ?
Related
I was trying to convert current working directory of a .bat script into linux format by using wsl wslpath. To show you it works on CMD:
However, when I put it in a .bat file, and changed %cd% to %~dp0, the path is empty:
test.bat contains:
FOR /F %%i IN ('wsl wslpath -a %~dp0') DO set lp=%%i
echo %lp%
Any idea why?
Try this:
echo "%cd%" -- "%~dp0"
%cd% returns the path without ending backslash. So you can add a second variable that clears it.
set "scriptDir=%~dp0"
set "scriptDir=%scriptDir:~0,-1%"
UPDATE (with string substitution only - use the toLinuxPath subroutine)
#echo off
call ::toLinuxPath "%userprofile%\AppData\Local\Temp" tempF
echo %tempF%
exit /b 0
:toLinuxPath [returnVariable - the result will be stored in it; If omitted will be only echoed]
setlocal
set "_path=%~p1"
set "name=%~nx1"
set "drive=%~d1"
set "rtrn=%~2"
set "result=/mnt/%drive:~0,1%%_path:\=/%%name%"
endlocal & (
if "%~2" neq "" (
set "%rtrn%=%result%"
) else (
echo %result%
)
)
Briefly - is there a simple svn command to tell us the "most recently changed branch"?
In more depth, as part of our build process, we're trying to detect the most recently-changed branch in Subversion, in order to perform further processing on that branch.
For example, if someone added the file:
http://server/svn/project/branches/Integration1/newfile.txt
we'd want to be able to determine the string:
http://server/svn/project/branches/Integration1
that is, the parent folder of the most recent change.
The closest we can find is to execute the following command:
svn log --verbose --limit 1 http://server/svn/project/
but it then gives a 4-line output that we'd need to parse, using batch.
We have a Jenkins build server with the Subversion plugin installed, which can detect the change to the overall subversion repository, but it only gives us the environment variables SVN_URL and SVN_REVISION, neither of which address our goal.
I would use:
svn log --verbose --quiet --limit 1 "http://server/svn/project/"
So you get rid of any commit log messages and have just a list of modified paths and a header. Then use a for /F loop loop to capture the paths:
rem // Capture output of `svn log`, skip header and hyphen-only lines:
for /F "skip=3 eol=- tokens=1*" %%I in ('
svn log --verbose --quiet --limit 1 "http://server/svn/project/"
') do echo(%%J
The tricky part is to derive the common root path of multiple items, which might be done like in the following script, for instance (see all the explanatory rem remarks in the code; provide the repository path http://server/svn/project/ as the first command line argument):
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_REPOPATH=%~1" & rem // (take the first argument as the repository path)
rem // Clear buffer for common root path:
set "COMM="
rem // Clear all variables beginning with `$`:
for /F "delims=" %%K in ('set $ 2^> nul') do set "%%K="
rem // Capture output of `svn log`, skip header and hyphen-only lines:
for /F "skip=3 eol=- tokens=1*" %%I in ('
svn log --verbose --quiet --limit 1 "%_REPOPATH%"
') do (
rem // Store currently iterated path:
set "ITEM=%%J"
rem // Check whether buffer for common root path is empty:
if not defined COMM (
rem // Buffer is empty, hence this is the first iteration:
set "COMM=%%J"
) else (
rem // Otherwise, store each `/`-separated path element in array `$ITEM[]`:
set /A "IDX=0"
setlocal EnableDelayedExpansion
for %%K in ("!ITEM:/=" "!") do (
for %%L in (!IDX!) do (
endlocal
set "$ITEM[%%L]=%%~K"
set /A "IDX+=1"
setlocal EnableDelayedExpansion
)
)
endlocal
rem // Store each element of buffered common root path in array `$COMM[]`:
set /A "CNT=IDX-1, IDX=0"
setlocal EnableDelayedExpansion
for %%K in ("!COMM:/=" "!") do (
for %%L in (!IDX!) do (
endlocal
set "$COMM[%%L]=%%~K"
set /A "IDX+=1"
setlocal EnableDelayedExpansion
)
)
rem // Determine the lower number of elements of `$ITEM[]` and `$COMM[]`:
if !CNT! geq !IDX! set /A "CNT=IDX-1"
rem // Loop through both arrays and write all common elements to buffer:
set "COMM=" & set "FLAG=#"
for /L %%L in (0,1,!CNT!) do (
if /I "!$ITEM[%%L]!" == "!$COMM[%%L]!" (
rem // The flag is just necessary to stop at the first difference:
if defined FLAG set "COMM=!COMM!!$COMM[%%L]!/"
) else set "FLAG="
)
rem // Transport the built common root path buffer beyond `endlocal`:
for /F "delims=" %%K in (""!COMM!"") do (
endlocal & set "COMM=%%~K"
)
)
)
setlocal EnableDelayedExpansion
if defined COMM (
rem // Check if there was only one path and just get get its parent in case:
if not "!COMM:~-1!" == "/" (
for %%K in ("!COMM:/=\!") do (
endlocal & set "COMM=%%~pK"
setlocal EnableDelayedExpansion
set "COMM=!COMM:\=/!"
)
)
rem // Return the finally retrieved common root path of all paths:
echo(!COMM:~1,-1!
)
endlocal
endlocal
exit /B
I don't know if that will work in your Jenkins environment, but here is what I would do in a standard (eg bash) shell. I use a terse svn log:
svn log ^/branches -l1 -q --incremental
Adding a pipe to parse it, the full command would be:
svn log ^/branches -l1 -q --incremental | sed -n "s/.*| \(.*\) |.*/\1/p"
Replace the caret (^) with http://server/svn/project/.
EDIT: to get the branch name, increase the verbosity of svn log with -v to print the modified paths, and adapt the sed command to extract the branch name. The following works for me:
svn log ^/branches -l1 -q -v | sed -n '4 s|.*/branches/||p'
or more aggressive:
svn log ^/branches -l1 -q -v | sed -nr '4 s|.*/branches/([^/]+).*|\1|p'
I am facing a problem with my following batch script, where I can see how the execution of the command %nr% --f !path2! never seems to happen and I don't understand the reason.
What am I doing wrong? Too many nested conditions ?
EDIT: adding WRONG code where comments are enabled
rem The call to this batch script will be this
rem C:/Projects/DevelopmentTools/SDKs/TP/B/Scrpt/Exg_Serial_Flasher.bat EF.hex DH.hex C:/Projects/DevelopmentTools/SDKs/TP/B/E/Output/CN/Exe/
setlocal enabledelayedexpansion
set nr=nr.exe
if "%1"=="" (
if "%2"=="" (
if "%3"=="" (
echo "[Error]"
set "runScript="
)
)
) else (
set "input1=%1"
set "input2=%2"
set "path3=%3%nr%"
set "myPath"=%3"
set "path1=!myPath!!input1!"
set "path2=!myPath!!input2!"
rem Control variable
set "runScript=true"
)
if defined runScript (
if exist "%path3%" (
%nr% --check
if exist !path1! (
%nr% --f !input1!
echo !ERRORLEVEL!
if !ERRORLEVEL! EQU 0 (
echo !input1! set correctly
if exist !path2! (
echo Setting !exgSerial!
%nr% --f !input2!
if !ERRORLEVEL! EQU 0 (
echo Everything went fine
)
)
)
)
)
)
Thanks!
I suggest following batch code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "ExeFile=nr.exe"
if "%~1" == "" goto ArgumentError
if "%~2" == "" goto ArgumentError
if not "%~3" == "" goto ProcessArguments
:ArgumentError
echo Error: %~nx0 must be called with three arguments.
exit /B 1
:ProcessArguments
rem Assign third argument to an environment variable.
set "FilePath=%~3"
rem Replace forward slashes by backslashes which is the directory separator on Windows.
set "FilePath=%FilePath:/=\%"
rem Make sure the file path ends with a backslash.
if not "%FilePath:~-1%" == "\" set "FilePath=%FilePath%\"
set "HexFile1=%FilePath%%~1"
set "HexFile2=%FilePath%%~2"
set "ExeFile=%FilePath%%ExeFile%"
if not exist "%ExeFile%" echo Error: "%ExeFile%" does not exist. & exit /B 2
if not exist "%HexFile1%" echo Error: "%HexFile1%" does not exist. & exit /B 3
if not exist "%HexFile2%" echo Error: "%HexFile2%" does not exist. & exit /B 3
"%ExeFile%" --check
"%ExeFile%" --f "%HexFile1%"
if errorlevel 1 echo Error: Processing "%HexFile1%" failed. & exit /B 4
"%ExeFile%" --f "%HexFile2%"
if errorlevel 1 echo Error: Processing "%HexFile2%" failed. & exit /B 4
echo Everything worked fine.
endlocal
An error condition is detected as soon as possible with resulting in exiting batch file processing with an appropriate error message and exit code.
There is no need for delayed environment variable expansion which makes processing the batch file faster and avoids problems with directory or file names containing an exclamation mark.
Name of a file or the file path can contain also command line critical characters like space or one of these characters &()[]{}^=;!'+,`~.
There are no nested IF conditions making successful execution flow straight from top to bottom.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~1 which expands to argument 1 with removing any surrounding quotes.
echo /?
endlocal /? ... used here implicit on exiting batch file processing with exit and explicit at end of batch file.
exit /?
goto /?
if /?
rem /?
setlocal /?
See also Single line with multiple commands using Windows batch file.
I think I found the issue, it has to do with the fact that the "echos" to debug seem to influence the script execution. So in the code of my question, if I enable the echos, the script will fail running whereas if I disable them( commented out as below), the script does work.
Nevertheless, I don't understand why it does fail with the echos in first instance.
Code with disabled echos and working
rem The call to this batch script will be this
rem C:/Projects/DevelopmentTools/SDKs/TP/B/Scrpt/Exg_Serial_Flasher.bat EF.hex DH.hex C:/Projects/DevelopmentTools/SDKs/TP/B/E/Output/CN/Exe/
setlocal enabledelayedexpansion
set nr=nr.exe
if "%1"=="" (
if "%2"=="" (
if "%3"=="" (
echo "[Error]"
set "runScript="
)
)
) else (
set "input1=%1"
set "input2=%2"
set "path3=%3%nr%"
set "myPath"=%3"
set "path1=!myPath!!input1!"
set "path2=!myPath!!input2!"
rem Control variable
set "runScript=true"
)
if defined runScript (
if exist "%path3%" (
%nr% --check
if exist !path1! (
%nr% --f !input1!
rem echo !ERRORLEVEL!
if !ERRORLEVEL! EQU 0 (
rem echo !input1! set correctly
if exist !path2! (
rem echo Setting !exgSerial!
%nr% --f !input2!
if !ERRORLEVEL! EQU 0 (
echo Everything went fine
)
)
)
)
)
)
I am working on multiple batch files and I want them to share some variables, so I created a batch file that has all these setups SetupEnv:
rem General setup
:: To pause or not after running a batch file
SET isPause = true
:: The directory where your source code is located
SET directory = D
:: The folders where your primary & secondary source code is located
:: I like to have two source code folders, if you don't then just have them pointing to the same folder
SET primary_source_code = \Dev\App
SET secondary_source_code = \Dev\App2
:::::::::::::::::::::::::::::::::::::::::::: XAMPP :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
rem If you're using XAMPP then set these up
:: Your destination folder
SET base_destination = C:\xampp\htdocs
:: The base url that is pointing to your destination folder (in most cases it's localhost)
SET base_url = http://10.0.2.65
:::::::::::::::::::::::::::::::::::::::::: Angular :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
rem If you're using angular set these up
:: The folder where you built code is copied
SET build_file = dist
And from another batch file I'm calling that file first:
::setup
call ../SetupEnv
echo %directory% dir
pause;
The problem is that even though the file runs smoothly and I can see in the outputs that things are being setup, the variables are not coming across to the file I'm calling it from. So in that example %directory% is not being printed.
EDIT
I also tried using Joey's answer:
::setup
for /f "delims=" %%x in (../SetupEnv.txt) do (set "%%x")
echo %directory% dir
pause
But that didn't work either and %directory% didn't get printed
setting variables in a called batchfile works, as long as you don't use setlocal in the called batchfile (there will be an implicite endlocal, when it returns, so the variables would get lost):
> type a.bat
set var=old
echo %var%
call b.bat
echo %var%
> type b.bat
set var=new
> a.bat
> set var=old
> echo old
old
> call b.bat
> set var=new
> echo new
new
>
for the alternative for solution, I would slightly change it to:
for /f "delims=" %%a in ('type b.bat^|findstr /bic:"set "') do %%a
This will only "execute" lines, that start with set (ignoring capitalization), so you can keep any comments inside that file.
Note: ... do set "%%a" adds another set to the line (you have already one in the file), resulting in set "set var=value", which you obviously don't want.
May be it's a bit too late, but nevertheless.
I've a loader script implementation to load a configuration file with a common format between Windows Batch and Unix Bash Shell scripts.
Format description:
# FORMAT:
# [<attributes>] <variable>[:[<class_name>]]=<value>
#
# <attributes>: Variable space separated attributes: export
# <variable>: Variable name corresponding to the regex: [_a-zA-Z][_a-zA-Z0-9]*
# <class_name>: class variant name: OSWIN | OSUNIX | BAT | SH
# OSWIN: Apply on Windows system including cygwin/mingw/msys subsystems.
# OSUNIX: Apply on Unix/Linux systems excluding cygwin/mingw/msys subsystems.
# BAT: Apply on Windows system when this file has loaded from the Windows batch script loader.
# SH: Apply on any system when this file has loaded from the Bash shell script loader.
#
# <value>: Can start by the `"` quote character, but two quotes does remove only when exist on both ends of a value.
#
Note: The export attribute has meaning only in the Unix Shell parser.
config file example:
export PYTHON_EXE_PATH:OSWIN="c:/python/x86/38/python.exe"
export PYTHON_EXE_PATH:OSUNIX=python3
export PYTHONDONTWRITEBYTECODE=1
MY_SHELL_SCRIPT:BAT=blabla.bat
MY_SHELL_SCRIPT:SH=blabla.sh
usage example:
call load_config.bat . . myvars.vars
This will generate the myvars.vars from the myvars.vars.in file and load it.
The script does generate an instance configuration file from a template file before parse an instance file. Implementation a bit complicated and might change in the future:
https://github.com/andry81/contools/tree/HEAD/Scripts/Tools/build/load_config.bat
https://github.com/andry81/contools/tree/HEAD/Scripts/Tools/build/.load_config
CAUTION:
Seems the stackoverflow incorrectly handles tabulation characters (and loses other characters like \x01) in the copy-pasted code, so the below code might not work if you copy it directly by CTRL+C. Use links above to directly download the script.
Old implementation (just for example):
#echo off
setlocal DISABLEDELAYEDEXPANSION
set "__CONFIG_IN_DIR=%~1"
set "__CONFIG_OUT_DIR=%~2"
set "__CONFIG_FILE=%~3"
if not defined __CONFIG_IN_DIR (
echo.%~nx0: error: input config directory is not defined.
exit /b 1
) >&2
if not defined __CONFIG_OUT_DIR (
echo.%~nx0: error: output config directory is not defined.
exit /b 2
) >&2
set "__CONFIG_IN_DIR=%__CONFIG_IN_DIR:\=/%"
set "__CONFIG_OUT_DIR=%__CONFIG_OUT_DIR:\=/%"
if "%__CONFIG_IN_DIR:~-1%" == "/" set "__CONFIG_IN_DIR=%__CONFIG_IN_DIR:~0,-1%"
if "%__CONFIG_OUT_DIR:~-1%" == "/" set "__CONFIG_OUT_DIR=%__CONFIG_OUT_DIR:~0,-1%"
if not exist "%__CONFIG_IN_DIR%\" (
echo.%~nx0: error: input config directory does not exist: "%__CONFIG_IN_DIR%".
exit /b 10
) >&2
if not exist "%__CONFIG_OUT_DIR%\" (
echo.%~nx0: error: output config directory does not exist: "%__CONFIG_OUT_DIR%".
exit /b 11
) >&2
if not exist "%__CONFIG_OUT_DIR%\%__CONFIG_FILE%" ^
if exist "%__CONFIG_IN_DIR%/%__CONFIG_FILE%.in" (
echo."%__CONFIG_IN_DIR%/%__CONFIG_FILE%.in" -^> "%__CONFIG_OUT_DIR%/%__CONFIG_FILE%"
type "%__CONFIG_IN_DIR:/=\%\%__CONFIG_FILE%.in" > "%__CONFIG_OUT_DIR%/%__CONFIG_FILE%"
)
rem load configuration files
if not exist "%__CONFIG_OUT_DIR%/%__CONFIG_FILE%" (
echo.%~nx0: error: config file is not found: "%__CONFIG_OUT_DIR%/%__CONFIG_FILE%".
exit /b 20
) >&2
for /F "usebackq eol=# tokens=* delims=" %%i in ("%__CONFIG_OUT_DIR%/%__CONFIG_FILE%") do (
endlocal
setlocal DISABLEDELAYEDEXPANSION
for /F "eol=# tokens=1,* delims==" %%j in ("%%i") do (
set "__VAR=%%j"
set "__VALUE=%%k"
call :PARSE_EXPR && (
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=1,* delims==" %%i in ("!__VAR!=!__VALUE!") do (
endlocal
endlocal
set "%%i=%%j"
)
type nul>nul
) || endlocal
)
)
exit /b 0
:PARSE_EXPR
if not defined __VAR exit /b 1
rem CAUTION:
rem Inplace trim of surrounded white spaces ONLY from left and right sequences as a whole for performance reasons.
rem
:TRIM_VAR_NAME
:TRIM_VAR_NAME_LEFT_LOOP
if not defined __VAR exit /b 1
if not ^%__VAR:~0,1%/ == ^ / if not ^%__VAR:~0,1%/ == ^ / goto TRIM_VAR_NAME_RIGHT_LOOP
set "__VAR=%__VAR:~1%"
goto TRIM_VAR_NAME_LEFT_LOOP
:TRIM_VAR_NAME_RIGHT_LOOP
if not ^%__VAR:~-1%/ == ^ / if not ^%__VAR:~-1%/ == ^ / goto TRIM_VAR_NAME_RIGHT_LOOP_END
set "__VAR=%__VAR:~0,-1%"
if not defined __VAR exit /b 1
goto TRIM_VAR_NAME_RIGHT_LOOP
:TRIM_VAR_NAME_RIGHT_LOOP_END
if not defined __VALUE exit /b 0
rem Replace a value quote characters by the \x01 character.
set "__VALUE=%__VALUE:"=%"
:TRIM_VAR_VALUE
setlocal DISABLEDELAYEDEXPANSION
:TRIM_VAR_VALUE_LEFT_LOOP
if not defined __VALUE exit /b 0
if not ^%__VALUE:~0,1%/ == ^ / if not ^%__VALUE:~0,1%/ == ^ / goto TRIM_VAR_VALUE_RIGHT_LOOP
set "__VALUE=%__VALUE:~1%"
goto TRIM_VAR_VALUE_LEFT_LOOP
:TRIM_VAR_VALUE_RIGHT_LOOP
if not ^%__VALUE:~-1%/ == ^ / if not ^%__VALUE:~-1%/ == ^ / goto TRIM_VAR_VALUE_RIGHT_LOOP_END
set "__VALUE=%__VALUE:~0,-1%"
if not defined __VALUE exit /b 0
goto TRIM_VAR_VALUE_RIGHT_LOOP
:TRIM_VAR_VALUE_RIGHT_LOOP_END
(
endlocal
set "__VALUE=%__VALUE%"
)
for /F "eol= tokens=1,* delims=:" %%i in ("%__VAR%") do (
set "__VAR=%%i"
set "__PLATFORM=%%j"
)
if not defined __VAR exit /b 1
if defined __PLATFORM ^
if not "%__PLATFORM%" == "BAT" ^
if not "%__PLATFORM%" == "WIN" ^
if not "%__PLATFORM%" == "OSWIN" exit /b 1
for /F "eol=# tokens=1,* delims= " %%i in ("%__VAR%") do (
set "__ATTR=%%i"
set "__VAR=%%j"
)
if not defined __VAR (
set "__VAR=%__ATTR%"
set "__ATTR="
)
if not defined __VAR exit /b 1
if ^/ == ^%__VALUE:~1,1%/ goto PREPARSE_VALUE
if not ^/ == ^%__VALUE:~0,1%/ goto PREPARSE_VALUE
if not ^/ == ^%__VALUE:~-1%/ goto PREPARSE_VALUE
:REMOVE_QUOTES
for /F "tokens=* delims=" %%i in ("%__VALUE:~1,-1%") do set "__VALUE=%%i"
if not defined __VALUE exit /b 0
goto PARSE_VALUE
:PREPARSE_VALUE
set __HAS_VALUE=0
for /F "eol=# tokens=* delims=" %%i in ("%__VALUE%") do set "__HAS_VALUE=1"
if %__HAS_VALUE% EQU 0 (
set "__VALUE="
exit /b 0
)
:PARSE_VALUE
rem recode quote and exclamation characters
set "__ESC__=^"
set __QUOT__=^"
set "__EXCL__=!"
set "__VALUE=%__VALUE:!=!__EXCL__!%"
set "__VALUE=%__VALUE:^=!__ESC__!%"
set "__VALUE=%__VALUE:=!__QUOT__!%"
exit /b 0
I'm trying to set the contents of a text file (it contains a single line of text) to a variable. To do this, I'm utilizing "set /p myvariable=
SetLocal EnableExtensions EnableDelayedExpansion
Set RegExist=No
Set RegUnins=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
Reg Query "%RegUnins%\{########-####-####-####-############}"
If "%errorlevel%"=="0" Set RegExist=Yes
If "%regexist%"=="Yes" (
Reg Query "%RegUnins%\{########-####-####-####-############}" /V "DisplayName" >"%temp%\appnam1.txt"
Find /I "This is the value for 'DisplayName'" "%temp%\appnam1.txt" >"%temp%\appnam2.txt"
More +2 "%temp%\appnam2.txt" >"%temp%\appnam3.txt"
Set /P _appnam=<"%temp%\appnam3.txt"
Set appnam=%_appnam:~24,53%
If "%appnam%"=="This is the value for 'DisplayName'" (
Echo - Current version installed: Performing reinstall...
Start "Reinstall" /B /High /Wait "\\server\installs\reinstall.exe"
) Else (
Echo - Previous version installed: Performing upgrade...
Start "Upgrade" /B /High /Wait "\\server\installs\upgrade.exe"
)
) Else (
Echo - Existing version not found: Performing new install...
Start "Install" /B /High /Wait "\\server\installs\new.install.exe"
)
However, even though the "%temp%\appnam3.txt" file contains the correct text, when I check the variables "%_appnam%" and "%appnam%" at those points in the code, they are blank. Therefore, if the machine does have the initial registry entry, it will always perform the upgrade process instead of the reinstall process. Any suggestions? I don't understand why the "set /p" line isn't working. Thanks in advance.
PLease use delayed expansion.
I tried to reproduce your case below. It seems the variable are set delayed, If you'll try to run you script several times, the values will be set.
#echo off
setlocal enableDelayedExpansion
set regexist=Yes
If "%regexist%"=="Yes" (
Set /P _appnam=<"C:\result.csv"
echo !_appnam!
Set appnam=!_appnam:~24,53!
echo !appnam!
)