From 23e8715022d3868ce1829ebed37814b40552183b Mon Sep 17 00:00:00 2001 From: Brandon Scott Date: Wed, 28 Aug 2019 23:23:23 -0500 Subject: [PATCH] Userland: Add 'which' command (#497) This mimics the shell's path resolution to locate the executable that would execute if typing it as a command. --- Userland/which.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Userland/which.cpp diff --git a/Userland/which.cpp b/Userland/which.cpp new file mode 100644 index 0000000000..7d9c50c357 --- /dev/null +++ b/Userland/which.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include + +int main(int argc, char** argv) +{ + if (argc < 2) { + printf("usage: which \n"); + return 0; + } + + char* filename = argv[1]; + + String path = getenv("PATH"); + if (path.is_empty()) + path = "/bin:/usr/bin"; + + auto parts = path.split(':'); + for (auto& part : parts) { + auto candidate = String::format("%s/%s", part.characters(), filename); + if(access(candidate.characters(), X_OK) == 0) { + printf("%s\n", candidate.characters()); + return 0; + } + } + + return 1; +}