MiniDevil As beautiful as a shell
builtin_unset.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* builtin_unset.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: baelgadi <baelgadi@student.42.fr> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2025/12/12 08:25:52 by baelgadi #+# #+# */
9 /* Updated: 2026/03/04 04:41:16 by baelgadi ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "builtins.h"
14 #include "libft.h"
15 
24 static int is_valid_unset_identifier(char *str)
25 {
26  int i;
27 
28  if (!str || !str[0])
29  return (0);
30  if (!ft_isalpha(str[0]) && str[0] != '_')
31  return (0);
32  i = 1;
33  while (str[i])
34  {
35  if (!ft_isalnum(str[i]) && str[i] != '_')
36  return (0);
37  i++;
38  }
39  return (1);
40 }
41 
50 static void remove_env_node(t_env **env, char *key)
51 {
52  t_env *current;
53 
54  current = *env;
55  while (current)
56  {
57  if (ft_strncmp(current->key, key, -1) == 0)
58  {
59  if (current->prev)
60  current->prev->next = current->next;
61  else
62  *env = current->next;
63  if (current->next)
64  current->next->prev = current->prev;
65  free(current->key);
66  if (current->value)
67  free(current->value);
68  free(current);
69  return ;
70  }
71  current = current->next;
72  }
73 }
74 
86 int builtin_unset(char **args, t_env **env)
87 {
88  int i;
89 
90  i = 1;
91  while (args[i])
92  {
93  if (args[i][0] == '-' && args[i][1])
94  {
95  ft_putstr_fd("minishell: unset: -", STDERR_FILENO);
96  ft_putchar_fd(args[i][1], STDERR_FILENO);
97  ft_putstr_fd(": invalid option\n", STDERR_FILENO);
98  return (2);
99  }
100  if (is_valid_unset_identifier(args[i]))
101  remove_env_node(env, args[i]);
102  i++;
103  }
104  return (0);
105 }
int builtin_unset(char **args, t_env **env)
Implement the unset command.
Definition: builtin_unset.c:86
static void remove_env_node(t_env **env, char *key)
Remove an env node by key from the doubly linked list.
Definition: builtin_unset.c:50
static int is_valid_unset_identifier(char *str)
Validate an identifier for unset.
Definition: builtin_unset.c:24
Shell builtin commands prototypes.
Environment variable (doubly linked list)
Definition: structs.h:87
char * key
Variable name.
Definition: structs.h:88
char * value
Value (NULL if export only)
Definition: structs.h:89
struct s_env * prev
Previous node.
Definition: structs.h:91
struct s_env * next
Next node.
Definition: structs.h:90