cmdcommand-prompt

Trying to make a menu in a windows command prompt


I have a batch file that gets run by the user typing:

usercompile filename

usercompile is a batch file that does this:

copy  /y %1.txt lib\incoming_file.txt

and then starts the compiler:

compiler.exe

The compiler has the "incoming_file" name hard-coded into linked source (this can't be chaged), so the current method is simply to copy the user file in and rename it to the known name and run the compiler.

I'd like to present the user with a list of files that are generated when a batch file is run, then the batch file would copy the selected file in, rename it (just like is done now).

So it would look like this:

Please choose a file to compile:
1) matthews_build
2) marks_build
3) lukes_build

and then the user would type 1 or 2 or 3 (in this case) and press enter. The batch file would copy that file to the known file name and launch the compiler. The one good thing is that the files that need to be listed all have a unique extension (.jal).

Any ideas?


Solution

  • One possible solution is to list all .jal files and give them an option number, store the result, and based on user input, look up the file based on the option number. As I know no way of storing such a result in memory (no array/hash table data type), only in a file, if a file can not be used, then the listing should be repeated in a deterministic way so that if we re-assign the option numbers, we get the same result. We can do it ensuring alphabetical ordering.
    Here is one implementation:
    BLOCK 1

    setlocal enabledelayedexpansion
    
    FOR /f "delims=|" %%i IN ('dir /b /on "yourpath\*.jal"') DO (
        set /a counter+=1
        echo !counter!^) %%~ni
    )
    
    endlocal
    

    The nested dir command ensures alphabetical ordering (reference.)
    A remark why I put a pipe (|) as a delimiter: if you don't define a delimiter, the default space will be used. If your file name contains space then it would be truncated. So I picked a character that is not valid in file names ensuring the whole file name is returned.

    Now if you get a number from the user by this:

    set /p option=Choose your option: 
    

    after this command (evaluating and possibly re-requesting the input) to do a lookup for the file you can repeat BLOCK 1 but replace the echo line with examining the option like this:

    if !counter! == %option%
    

    and put those commands in the if block to do whatever you want to do with the file (for debugging, put back the echo command).