diff --git a/src/main/java/com/mycmd/commands/CdCommand.java b/src/main/java/com/mycmd/commands/CdCommand.java index bb9c3a3..1dc8b12 100644 --- a/src/main/java/com/mycmd/commands/CdCommand.java +++ b/src/main/java/com/mycmd/commands/CdCommand.java @@ -7,14 +7,31 @@ public class CdCommand implements Command { @Override public void execute(String[] args, ShellContext context) { + // If no argument, print current directory if (args.length == 0) { System.out.println(context.getCurrentDir().getAbsolutePath()); return; } - File newDir = new File(args[0]); - if (!newDir.isAbsolute()) { - newDir = new File(context.getCurrentDir(), args[0]); + + String dir = args[0]; + File newDir; + + // Handle "cd .." (go to parent directory) + if (dir.equals("..")) { + File parent = context.getCurrentDir().getParentFile(); + if (parent == null) { + System.out.println("Already at the root directory."); + return; + } + newDir = parent; + } else { + newDir = new File(dir); + if (!newDir.isAbsolute()) { + newDir = new File(context.getCurrentDir(), dir); + } } + + // Change directory if valid if (newDir.exists() && newDir.isDirectory()) { context.setCurrentDir(newDir); } else {