Execute Anonymous Apex

You can execute an anonymous block of Apex code in an org with the apex run Salesforce CLI command.
  1. Open a terminal (macOS and Linux) or command prompt Windows and change to your Salesforce DX project directory.
  2. Run the apex run command with no flags to open an interactive shell. At the prompt, enter all your Apex code; press CTRL-D when you're finished. Your code is then executed in a single execute anonymous request in the specified org, or the default org if you don’t specify one.
    1sf apex run --target-org myscratch
    This output shows an example of executing the Apex code system.debug ('Hello world!');
    1Start typing Apex code. Press the Enter key after each line, then press CTRL+D when finished.
    2system.debug ('Hello world!');
    3Compiled successfully.
    4Executed successfully.
    5
    658.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO
    7Execute Anonymous: system.debug ('Hello world!');
    814:23:06.174 (174742273)|USER_INFO|[EXTERNAL]|0058H000005QWcE|test-ux9lpg9jyyqt@example.com|(GMT-07:00) Pacific Daylight Time (America/Los_Angeles)|GMT-07:00
    914:23:06.174 (174785450)|EXECUTION_STARTED
    1014:23:06.174 (174792639)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
    1114:23:06.174 (175417814)|USER_DEBUG|[1]|DEBUG|Hello world!
    1214:23:06.175 (175529797)|CUMULATIVE_LIMIT_USAGE
    1314:23:06.175 (175529797)|LIMIT_USAGE_FOR_NS|(default)|
    14  Number of SOQL queries: 0 out of 100
    15  Number of query rows: 0 out of 50000
    16  Number of SOSL queries: 0 out of 20
    17  Number of DML statements: 0 out of 150
    18  Number of Publish Immediate DML: 0 out of 150
    19  Number of DML rows: 0 out of 10000
    20  Maximum CPU time: 0 out of 10000
    21  Maximum heap size: 0 out of 6000000
    22  Number of callouts: 0 out of 100
    23  Number of Email Invocations: 0 out of 10
    24  Number of future calls: 0 out of 50
    25  Number of queueable jobs added to the queue: 0 out of 50
    26  Number of Mobile Apex push calls: 0 out of 10
    27
    2814:23:06.175 (175529797)|CUMULATIVE_LIMIT_USAGE_END
    29
    3014:23:06.174 (175598235)|CODE_UNIT_FINISHED|execute_anonymous_apex
    3114:23:06.174 (175617689)|EXECUTION_FINISHED

    Use the --file flag to execute Apex code in a file rather than interactively.

    1sf apex run --file ~/test.apex