package CustomCommands; use Cwd; use File::HomeDir; our %COMMANDS = ( # Built-in commands 'cd' => sub { my ($command) = @_; if ($command =~ /^cd\s*(.*)/) { my $dir = $1 || $ENV{HOME}; chdir $dir or warn "Could not change to directory $dir: $!"; return 1; } return 0; }, 'export' => sub { my ($command, $env) = @_; if ($command =~ /^export\s+(\w+)=(.*)/) { $ENV{$1} = $2; $env->set($1, $2); return 1; } return 0; }, 'env' => sub { print "$_=$ENV{$_}\n" for sort keys %ENV; return 1; }, # Example custom commands 'quit' => sub { exit; return 1; } ); sub handle { my ($command, $env) = @_; #print STDERR "DEBUG: Handling command: $command\n"; # Check if this is a custom command foreach my $cmd (keys %COMMANDS) { if ($command =~ /^$cmd\b/) { #print STDERR "DEBUG: Found custom command: $cmd\n"; return $COMMANDS{$cmd}->($command, $env) ? 1 : 0; } } # Check if it's a system command my ($cmd_name) = split(/\s+/, $command); #print STDERR "DEBUG: Checking system command: $cmd_name\n"; # Check PATH directly foreach my $path (split(/:/, $ENV{PATH})) { my $full_path = "$path/$cmd_name"; if (-x $full_path) { my $pid = fork(); die "Fork failed: $!" unless defined $pid; if ($pid == 0) { # Child exec($full_path, split(/\s+/, $command)) or die "Exec failed: $!"; } waitpid($pid, 0); # Wait for child return 2; } } #print STDERR "DEBUG: Command not found: $command\n"; return -1; # Command not found } 1;