MiniDevil As beautiful as a shell
builtin_export.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* builtin_export.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: baelgadi <baelgadi@student.42.fr> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2025/12/11 22:35:14 by baelgadi #+# #+# */
9 /* Updated: 2026/03/04 04:41:09 by baelgadi ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "builtins.h"
14 #include "libft.h"
15 #include "env.h"
16 
26 static int is_valid_identifier(char *str)
27 {
28  int i;
29 
30  if (!str || !str[0])
31  return (0);
32  if (!ft_isalpha(str[0]) && str[0] != '_')
33  return (0);
34  i = 1;
35  while (str[i] && str[i] != '=')
36  {
37  if (str[i] == '+')
38  {
39  if (str[i + 1] == '=')
40  return (1);
41  else
42  return (0);
43  }
44  if (!ft_isalnum(str[i]) && str[i] != '_')
45  return (0);
46  i++;
47  }
48  return (1);
49 }
50 
56 static void print_export_error(char *arg)
57 {
58  ft_putstr_fd("minishell: export: `", STDERR_FILENO);
59  ft_putstr_fd(arg, STDERR_FILENO);
60  ft_putstr_fd("': not a valid identifier\n", STDERR_FILENO);
61 }
62 
70 static int export_one(char *arg, t_env **env)
71 {
72  if (!is_valid_identifier(arg))
73  {
74  print_export_error(arg);
75  if (arg[0] == '-')
76  return (2);
77  return (1);
78  }
79  if (ft_strnstr(arg, "+=", ft_strlen(arg)))
80  export_append(env, arg);
81  else if (ft_strchr(arg, '='))
82  export_assign(env, arg);
83  else
84  export_no_value(env, arg);
85  return (0);
86 }
87 
99 int builtin_export(char **args, t_env **env)
100 {
101  int i;
102  int status;
103  int tmp;
104 
105  if (!args[1])
106  return (print_sorted_export(*env), 0);
107  status = 0;
108  i = 1;
109  while (args[i])
110  {
111  tmp = export_one(args[i++], env);
112  if (tmp > status)
113  status = tmp;
114  }
115  return (status);
116 }
static int is_valid_identifier(char *str)
Validate an export identifier (KEY or KEY= or KEY+=)
int builtin_export(char **args, t_env **env)
Implement the export command.
static int export_one(char *arg, t_env **env)
Process an export argument.
static void print_export_error(char *arg)
Print export error.
Shell builtin commands prototypes.
Environment variable management prototypes.
void export_no_value(t_env **env, char *key)
Export a variable with no value (export KEY)
Definition: export_ops.c:26
void export_assign(t_env **env, char *arg)
Export a variable with a value (export KEY=value)
Definition: export_ops.c:55
void export_append(t_env **env, char *arg)
Export a variable with append (export KEY+=value)
Definition: export_ops.c:104
void print_sorted_export(t_env *env)
Print all env vars sorted in alphabetical order, in declare -x format.
Definition: export_utils.c:120
Environment variable (doubly linked list)
Definition: structs.h:87