From: Ahmad Fatoum <[email protected]>

We have no $PWD an we would have to populate it globally, because all of
barebox shares a single working directory. What we can easily do however
is populate $OLDPWD to give shell scripts a way to resolve some
artifacts relatively and then revert back to the original working
directory, so implement that as well as cd -.

Co-developed-by: Claude Sonnet 4.5 <[email protected]>
Signed-off-by: Ahmad Fatoum <[email protected]>
---
 commands/cd.c | 30 ++++++++++++++++++++++++++----
 1 file changed, 26 insertions(+), 4 deletions(-)

diff --git a/commands/cd.c b/commands/cd.c
index 0238919bf26c..e42beb79b282 100644
--- a/commands/cd.c
+++ b/commands/cd.c
@@ -12,26 +12,48 @@
 #include <command.h>
 #include <fs.h>
 #include <errno.h>
+#include <environment.h>
 
 static int do_cd(int argc, char *argv[])
 {
+       const char *target_dir;
+       char *old_pwd;
        int ret;
 
-       if (argc == 1)
-               ret = chdir("/");
-       else
-               ret = chdir(argv[1]);
+       if (argc == 1) {
+               target_dir = "/";
+       } else if (strcmp(argv[1], "-")) {
+               target_dir = argv[1];
+       } else {
+               /* cd - switches to previous directory */
+               target_dir = getenv("OLDPWD");
+               if (!target_dir) {
+                       printf("cd: OLDPWD not set\n");
+                       return 1;
+               }
+               /* Print the directory we're changing to, like bash does */
+               printf("%s\n", target_dir);
+       }
 
+       /* Save current directory before changing */
+       old_pwd = xstrdup(getcwd());
+
+       ret = chdir(target_dir);
        if (ret) {
                perror("chdir");
                return 1;
        }
 
+       setenv("OLDPWD", old_pwd);
+       free(old_pwd);
+
        return 0;
 }
 
 BAREBOX_CMD_HELP_START(cd)
 BAREBOX_CMD_HELP_TEXT("If called without an argument, change to the root 
directory '/'.")
+BAREBOX_CMD_HELP_TEXT("Use 'cd -' to change to the previous directory.")
+BAREBOX_CMD_HELP_TEXT("Sets OLDPWD environment variables.")
 BAREBOX_CMD_HELP_END
 
 BAREBOX_CMD_START(cd)
-- 
2.47.3


Reply via email to