minishell/src/executing/simple_cmd/builtin_cd.c

65 lines
1.9 KiB
C
Raw Normal View History

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* builtin_cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: khais <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/03/31 16:20:17 by khais #+# #+# */
/* Updated: 2025/03/31 20:04:28 by khais ### ########.fr */
/* */
/* ************************************************************************** */
#include "builtins.h"
#include "ft_printf.h"
#include "libft.h"
#include <unistd.h>
2025-03-31 16:40:01 +02:00
#include "../../env/env_manip.h"
#include "../../ft_errno.h"
static void ft_chdir(char *path, t_minishell *app)
{
2025-03-31 17:05:30 +02:00
if (path[0] == '\0')
app->last_return_value = 0;
else if (chdir(path) == 0)
app->last_return_value = 0;
else
{
app->last_return_value = 1;
ft_errno(FT_EERRNO);
ft_perror("minishell: cd");
}
}
static void chdir_home(t_minishell *app)
{
char *home;
home = env_get_val(app->env, "HOME");
if (home == NULL)
{
app->last_return_value = 1;
ft_dprintf(STDERR_FILENO, "minishell: cd: HOME not set\n");
}
else
ft_chdir(home, app);
}
t_builtin_type builtin_cd(t_simple_cmd *cmd, t_minishell *app)
{
t_worddesc *arg;
if (wordlist_get(cmd->words, 2) != NULL)
{
ft_dprintf(STDERR_FILENO, "minishell: cd: too many arguments\n");
app->last_return_value = 1;
return (BUILTIN_CD);
}
arg = wordlist_get(cmd->words, 1);
if (arg == NULL)
chdir_home(app);
else
ft_chdir(arg->word, app);
return (BUILTIN_CD);
}