sys_run_command_with_exit_code Subroutine

public subroutine sys_run_command_with_exit_code(command, output_file, exit_file)

Run a command and capture output and exit code to files This is a portable way to replace Unix "command > output 2>&1; echo $? > exit_file"

Arguments

Type IntentOptional Attributes Name
character(len=*), intent(in) :: command
character(len=*), intent(in) :: output_file
character(len=*), intent(in) :: exit_file

Source Code

    subroutine sys_run_command_with_exit_code(command, output_file, exit_file)
        character(len=*), intent(in) :: command, output_file, exit_file
        character(len=2048) :: full_command
        integer :: exit_code, unit

        if (get_os_type() == OS_WINDOWS) then
            ! Windows: Run command first, then check ERRORLEVEL separately
            ! This ensures we capture the exit code of the command, not the echo
            call execute_command_line(trim(command)//' > "'//trim(escape_shell_arg(output_file))//'" 2>&1', exitstat=exit_code)
            ! Write the exit code manually
            open (newunit=unit, file=trim(exit_file), status='replace')
            write (unit, '(i0)') exit_code
            close (unit)
            return
        else
            ! Unix: Use shell to run command and capture exit code
       full_command = '('//trim(command)//') > "'//trim(escape_shell_arg(output_file)) &
                         //'" 2>&1; echo $? > "'//trim(escape_shell_arg(exit_file))//'"'
        end if

        call execute_command_line(full_command)
    end subroutine sys_run_command_with_exit_code