Search code examples
batch-filecommand-promptpiping

Piping multiple values into a program in a batch script


I'm writing my own simple system allowing me to automatically sign APKs before they are uploaded to GPlay. I've got a batch file that does the signing; and a "wrapper" batch file, the content of which will be run on the command line by Jenkins post-build.

sign_apks.bat:

@echo off

set /p job= "Enter job name: "
set /p alias= "Enter key alias: "
set /p mobile= "Sign mobile? (y/n): "
set /p wear= "Sign wear? (y/n): "

echo.
echo "%job%"
echo "%alias%"
echo "%mobile%"
echo "%wear%"

[the rest of the code is sensitive so is emitted, but these variables are used later]

wrapper code:

@echo off

(echo test
echo test
echo y
echo y)| call sign_apks.bat

This article showed me how to pipe values into a program. To quote from the answer,:

Multiple lines can be entered like so:

(echo y
echo n) | executable.exe

...which will pass first 'y' then 'n'.

However, this doesn't work. This is the output I get when running the wrapper code:

Enter job name: Enter key alias: Sign mobile? (y/n): Sign wear? (y/n):
"test "
""
""
""

Help?


Solution

  • You know, the easiest solution would be to supply job, alias, mobile, and wear as script arguments rather than trying to pipe them into stdin. You can still set /p if not defined, if you wish to run interactively without arguments.

    @echo off
    setlocal
    
    set "job=%~1"
    set "alias=%~2"
    set "mobile=%~3"
    set "wear=%~4"
    
    if not defined job set /p "job=Enter job name: "
    if not defined alias set /p "alias=Enter key alias: "
    if not defined mobile set /p "mobile=Sign mobile? (y/n): "
    if not defined wear set /p "wear=Sign wear? (y/n): "
    
    echo.
    echo "%job%"
    echo "%alias%"
    echo "%mobile%"
    echo "%wear%"
    

    Then when you call sign_apks.bat, just call it like this:

    call sign_apks.bat test test y y