#!/usr/bin/c++script // Demonstration of the COMMAND object progdesc ("Demonstration of the COMMAND object"); // Using the ls command cout << "================ ls\n"; for (auto &&f:COMMAND("ls").run()){ cout << format ("{}\n",f.line); } // Using the ls -l cout << "================ ls -l\n"; for (auto &&f:COMMAND("ls -l").run()){ cout << format ("{}\n",f.line); } // Using an unknown command // We see that normal output and error messages are merge in a single range // The function is_error() and is_output() are used to tell them apart cout << "================ unknown\n"; for (auto &&f:COMMAND("unknown").run()){ if (f.is_error()){ cout << format ("error message: {}\n",f.line); }else if (f.is_output()){ cout << format ("normal output: {}\n",f.line); } } // The command may be any bash expression. cout << "================ ls -l | tail -2\n"; for (auto &&f:COMMAND("ls -l | tail -2").run()){ cout << format ("{}\n",f.line); } // Here we use tests/printlines to produce normal output and error messages. // We use COMMAND::store_errors() which copies to the vector called errors // and filter out all error messages. So in the loop, we only get normal output. COMMAND c4 ("tests/printlines -n5 -e3"); cout << format("================ {}\n",c4.get()); vector errors; for (auto &&f:c4.run() | COMMAND::store_error(errors)){ cout << format ("{}\n",f.line); } for (auto &e:errors) cout << format ("errors {}\n",e);