dryrun.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 int main(int argc, char *argv[]) 6 { 7 // Check if the DRYRUN environment variable is set 8 if (getenv("DRYRUN") == NULL) { 9 // DRYRUN is not set, so evaluate the arguments starting from the second argument as if they were part of a single system command 10 if (argc > 1) { 11 int command_size = 0; 12 for (int i = 1; i < argc; i++) { 13 command_size += strlen(argv[i]) + 1; // + 1 for the space character 14 } 15 char command[command_size]; 16 17 // Concatenate all of the arguments starting from the second argument into a single string, respecting the original quoting 18 strcpy(command, argv[1]); 19 for (int i = 2; i < argc; i++) { 20 strcat(command, " "); 21 strcat(command, argv[i]); 22 } 23 24 // Evaluate the command using the system function 25 int result = system(command); 26 return result; 27 } 28 } else { 29 30 // DRYRUN is set. dont run, just print 31 for (int i = 0; i < argc; i++) { 32 printf("%s", argv[i]); 33 printf((i < argc-1)?" ":"\n"); 34 } 35 } 36 return 0; 37 } 38 39 /* 40 * 20221203 - initially written with chatgpt (https://chat.openai.com/chat) 41 * > write a c program where if DRYRUN is not set, evaluate inputs as if they were a system command 42 * > initialize command size to be the sum of the size of all arguments 43 44 This program is similar to the previous examples, but it takes care to respect the original quoting of the arguments when concatenating them into a single string. If DRYRUN is not set, the main function uses a for loop to iterate over the argv array starting from the second argument. For each argument, it checks if the argument is already quoted (i.e. if it starts with a double quote character). If the argument is already quoted, it is simply appended to the command string as-is. Otherwise, the argument is quoted before it is appended to the command string. 45 46 Once all of the arguments have been concatenated into the command string, it is passed to the system function, which evaluates it as a command and returns the result code. This result code is printed to the standard output stream using the printf function. 47 48 If DRYRUN is set or if only one argument was provided, the program simply ends without doing anything. 49 50 Note that this is just one way to write a C program that evaluates all of the program arguments starting from the second argument as if they were part of a single system command, while taking care to respect the original quoting of the arguments, if the DRYRUN environment variable is not set. There may be other ways to accomplish this. Additionally, using the system function to evaluate commands can be dangerous and should be used with caution. 51 */