Intente escribir un script por lotes para encontrar todos los archivos .c en el directorio actual y compilarlos

Intente escribir un script por lotes para encontrar todos los archivos .c en el directorio actual y compilarlos

Estaba intentando escribir un makeanálogo en Windows, usando archivos por lotes.

Pero soy un novato en secuencias de comandos por lotes, aquí está mi intento:

Estoy intentando crear un script por lotes que busque todos los archivos .c en el directorio actual y los compile.

@echo off
for %%a in (*) do (
    if "%%a" == "*.c" (
        gcc "%%a" -o "%%a.exe"
    )
)

Creo que debería funcionar y hay un problema de sintaxis, pero realmente no tengo idea, podría haber otros problemas también. Además, si hay una mejor manera de lograrlo, especifique

Respuesta1

@echo off

for %%i in ("%~dp0*.C")do gcc "%%~i" -o "%%~dpni.exe"

  • Obs.: 1.Para usar el código anterior, necesita tener una copia de este script/bat en cada carpeta donde lo usará...

Puede dirigir su bucle para que utilice la misma unidad y carpeta donde se está ejecutando su archivo bat, señalando así ya el.carchivos que se utilizarán y los ejecutables que se crearán:

  • Uso y comprensión%~DP0
Same Drive: \Path where your file.bat       is:
    |-----|  |------|       |--------|
      C:     \Folder\        file.bat
    | %~D |  | %~P  |       |   %~0  | ==>  %~DP0
  • Uso y comprensión%%~NXi
Same Name      eXtension  of   file.C   listed in loop
    |-------|  |--------|     |---------|
     Program       .C          Program.C
    | %%~N  |  |  %%~X  |     |  %%~NX  | ==>  %~NXi
  • Uso y comprensión%%~DPNXi
Same Drive:   \Path     \Name       eXtension  of  file.C   listed in loop
    |------|  |------|  |--------| |--------|
       C:     \Folder\   Program       .C 
    | %%~D |  | %%~P  | |  %%~N  | |  %%~X  | ==>  %%~DPNXi

  • Obs.: 2.UsarFor /?para obtener más información sobre los modificadores:
In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    %~sI        - expanded path contains short names only
    %~aI        - expands %I to file attributes of file
    %~tI        - expands %I to date/time of file
    %~zI        - expands %I to size of file
    %~$PATH:I   - searches the directories listed in the PATH
                   environment variable and expands %I to the
                   fully qualified name of the first one found.
                   If the environment variable name is not
                   defined or the file is not found by the
                   search, then this modifier expands to the
                   empty string

The modifiers can be combined to get compound results:

    %~dpI       - expands %I to a drive letter and path only
    %~nxI       - expands %I to a file name and extension only
    %~fsI       - expands %I to a full path name with short names only
    %~dp$PATH:I - searches the directories listed in the PATH
                   environment variable for %I and expands to the
                   drive letter and path of the first one found.
    %~ftzaI     - expands %I to a DIR like output line

In the above examples %I and PATH can be replaced by other valid
values.  The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.
  • Obs.: 3. %~f0es lo mismo que este%~DPNX0

You can get the pathname of the batch script itself with %0, parameter xtensions
can be applied to this so %~dp0 will return the Drive and Path to the batch scrip
e.g. W:\scripts\ and %~f0 will return the full pathname W:\scripts\mybatch.cmd
Fuente vinculada ass64.com


@echo off

for %%i in ("%~dpnx1\*.C")do gcc "%%~i" -o "%%~dpni.exe"

Guardar este script con cualquier nombre que sea fácil de recordar, comoCGGc.cmd, poner enC:\Windows\SYSTEM32carpeta, donde aparece esta carpeta en el%PATH%del sistema, y ​​será encontrado y ejecutado sin necesidad de estar en la misma carpeta donde se encuentran sus archivos.*.Cson.

Puede usar un solo bat para aplicarlo a cualquier carpeta, simplemente pase la carpeta actual como parámetro, ya que el bat ya se ha definido*.Cpara manejar, informa solo una carpeta, usando una ruta relativa como argumento,.:

/Los scripts también aceptan argumentos/parámetros durante la ejecución.


Para usar este bate, simplemente pasa el argumento..:

>GCCc  .

Donde este punto (.) se refiere a la ruta a la carpeta actual donde está invocando el bat, este será un argumento que Forel bucle usará como elDrive\Path\Folder_Name.eXtension\ de argumento%~1, y elnxestán presentes para evitar un error:

Full Stop Bug
Although Win32 will not recognise any file or directory name that begins or ends with a '.' (period / full stop) it is possible to include a Full Stop in the middle of a directory name and this can cause issues with FOR /D.   Parameter expansion will treat a Full Stop as a file extension, so for a directory name like "Sample 2.6.4" the output of %%~nG will be truncated to "Sample 2.6" to return the whole folder name use %%G or %%~nxG



información relacionada