mail archive of the barebox mailing list
 help / color / mirror / Atom feed
* [PATCH] commands: cd: implement support for cd - and $OLDPWD
@ 2026-01-20 12:27 Ahmad Fatoum
  0 siblings, 0 replies; only message in thread
From: Ahmad Fatoum @ 2026-01-20 12:27 UTC (permalink / raw)
  To: barebox; +Cc: Ahmad Fatoum, Claude Sonnet 4.5

From: Ahmad Fatoum <a.fatoum@barebox.org>

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 <noreply@anthropic.com>
Signed-off-by: Ahmad Fatoum <a.fatoum@barebox.org>
---
 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




^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2026-01-20 12:28 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-01-20 12:27 [PATCH] commands: cd: implement support for cd - and $OLDPWD Ahmad Fatoum

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox