1 /* variables.c -- Functions for hacking shell variables. */
3 /* Copyright (C) 1987,1989 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 1, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
23 #include "bashtypes.h"
24 #include "posixstat.h"
30 #if defined (HAVE_UNISTD_H)
41 #include "execute_cmd.h"
43 #include "mailcheck.h"
46 #include "builtins/getopt.h"
47 #include "builtins/common.h"
49 #if defined (READLINE)
50 # include "bashline.h"
51 # include <readline/readline.h>
53 # include <tilde/tilde.h>
57 # include "bashhist.h"
58 # include <readline/history.h>
61 /* Variables used here and defined in other files. */
62 extern int posixly_correct;
63 extern int variable_context, line_number;
64 extern int interactive, interactive_shell, login_shell;
65 extern int subshell_environment, indirection_level;
66 extern int build_version, patch_level;
67 extern char *dist_version, *release_status;
68 extern char *shell_name;
69 extern char *primary_prompt, *secondary_prompt;
70 extern char *current_host_name;
71 extern Function *this_shell_builtin;
72 extern char *this_command_name;
73 extern time_t shell_start_time;
75 /* The list of shell variables that the user has created, or that came from
77 HASH_TABLE *shell_variables = (HASH_TABLE *)NULL;
79 /* The list of shell functions that the user has created, or that came from
81 HASH_TABLE *shell_functions = (HASH_TABLE *)NULL;
83 /* The current variable context. This is really a count of how deep into
84 executing functions we are. */
85 int variable_context = 0;
87 /* The array of shell assignments which are made only in the environment
88 for a single command. */
89 char **temporary_env = (char **)NULL;
91 /* The array of shell assignments which are in the environment for the
92 execution of a shell function. */
93 char **function_env = (char **)NULL;
95 /* The array of shell assignments which are made only in the environment
96 for the execution of a shell builtin command which may cause more than
97 one command to be executed (e.g., "source"). */
98 char **builtin_env = (char **)NULL;
100 /* Some funky variables which are known about specially. Here is where
101 "$*", "$1", and all the cruft is kept. */
102 char *dollar_vars[10];
103 WORD_LIST *rest_of_args = (WORD_LIST *)NULL;
105 /* The value of $$. */
106 int dollar_dollar_pid;
108 /* An array which is passed to commands as their environment. It is
109 manufactured from the union of the initial environment and the
110 shell variables that are marked for export. */
111 char **export_env = (char **)NULL;
112 static int export_env_index;
113 static int export_env_size;
115 /* Non-zero means that we have to remake EXPORT_ENV. */
116 int array_needs_making = 1;
118 /* The number of times BASH has been executed. This is set
119 by initialize_variables (). */
122 static char *have_local_variables;
123 static int local_variable_stack_size;
125 /* Some forward declarations. */
126 static void set_home_var ();
127 static void set_shell_var ();
128 static char *get_bash_name ();
129 static void initialize_shell_level ();
130 static void uidset ();
131 static void initialize_dynamic_variables ();
132 static void make_vers_array ();
133 static void sbrand (); /* set bash random number generator. */
134 static int qsort_var_comp ();
136 /* Make VAR be auto-exported. VAR is a pointer to a SHELL_VAR. */
137 #define set_auto_export(var) \
138 do { var->attributes |= att_exported; array_needs_making = 1; } while (0)
140 /* Initialize the shell variables from the current environment.
141 If PRIVMODE is nonzero, don't import functions from ENV or
144 initialize_shell_variables (env, privmode)
148 char *name, *string, *temp_string;
149 int c, char_index, string_index, string_length;
152 if (shell_variables == 0)
153 shell_variables = make_hash_table (0);
155 if (shell_functions == 0)
156 shell_functions = make_hash_table (0);
158 for (string_index = 0; string = env[string_index++]; )
162 while ((c = *string++) && c != '=')
164 if (string[-1] == '=')
165 char_index = string - name - 1;
167 /* If there are weird things in the environment, like `=xxx' or a
168 string without an `=', just skip them. */
172 /* ASSERT(name[char_index] == '=') */
173 name[char_index] = '\0';
174 /* Now, name = env variable name, string = env variable value, and
175 char_index == strlen (name) */
177 /* If exported function, define it now. */
178 if (privmode == 0 && STREQN ("() {", string, 4))
180 string_length = strlen (string);
181 temp_string = xmalloc (3 + string_length + char_index);
183 strcpy (temp_string, name);
184 temp_string[char_index] = ' ';
185 strcpy (temp_string + char_index + 1, string);
187 sprintf (temp_string, "%s %s", name, string);
190 parse_and_execute (temp_string, name, SEVAL_NONINT|SEVAL_NOHIST);
192 /* Ancient backwards compatibility. Old versions of bash exported
193 functions like name()=() {...} */
194 if (name[char_index - 1] == ')' && name[char_index - 2] == '(')
195 name[char_index - 2] = '\0';
197 if (temp_var = find_function (name))
199 temp_var->attributes |= (att_exported | att_imported);
200 array_needs_making = 1;
203 report_error ("error importing function definition for `%s'", name);
205 if (name[char_index - 1] == ')' && name[char_index - 2] == '\0')
206 name[char_index - 2] = '(';
208 #if defined (ARRAY_VARS)
210 /* Array variables may not yet be exported. */
211 else if (*string == '(' && string[1] == '[' && strchr (string, ')'))
214 temp_string = extract_array_assignment_list (string, &string_length);
215 temp_var = assign_array_from_string (name, temp_string);
217 temp_var->attributes |= (att_exported | att_imported);
218 array_needs_making = 1;
224 temp_var = bind_variable (name, string);
225 temp_var->attributes |= (att_exported | att_imported);
226 array_needs_making = 1;
229 name[char_index] = '=';
232 /* If we got PWD from the environment, update our idea of the current
233 working directory. In any case, make sure that PWD exists before
234 checking it. It is possible for getcwd () to fail on shell startup,
235 and in that case, PWD would be undefined. */
236 temp_var = find_variable ("PWD");
237 if (temp_var && imported_p (temp_var) &&
238 (temp_string = value_cell (temp_var)) &&
239 same_file (temp_string, ".", (struct stat *)NULL, (struct stat *)NULL))
240 set_working_directory (temp_string);
243 temp_string = get_working_directory ("shell-init");
246 temp_var = bind_variable ("PWD", temp_string);
247 set_auto_export (temp_var);
252 /* According to the Single Unix Specification, v2, $OLDPWD is an
253 `environment variable' and therefore should be auto-exported.
254 Make a dummy invisible variable for OLDPWD, and mark it as exported. */
255 temp_var = bind_variable ("OLDPWD", (char *)NULL);
256 temp_var->attributes |= (att_exported | att_invisible);
258 /* Set up initial value of $_ */
259 temp_var = bind_variable ("_", dollar_vars[0]);
261 /* Remember this pid. */
262 dollar_dollar_pid = (int)getpid ();
264 /* Now make our own defaults in case the vars that we think are
265 important are missing. */
266 temp_var = set_if_not ("PATH", DEFAULT_PATH_VALUE);
267 set_auto_export (temp_var);
269 temp_var = set_if_not ("TERM", "dumb");
270 set_auto_export (temp_var);
273 /* set node id -- don't import it from the environment */
276 qnx_nidtostr (getnid (), node_name, sizeof (node_name));
277 temp_var = bind_variable ("NODE", node_name);
278 set_auto_export (temp_var);
282 /* set up the prompts. */
283 if (interactive_shell)
285 #if defined (PROMPT_STRING_DECODE)
286 set_if_not ("PS1", primary_prompt);
288 if (current_user.uid == -1)
289 get_current_user_info ();
290 set_if_not ("PS1", current_user.euid == 0 ? "# " : primary_prompt);
292 set_if_not ("PS2", secondary_prompt);
294 set_if_not ("PS4", "+ ");
296 /* Don't allow IFS to be imported from the environment. */
297 temp_var = bind_variable ("IFS", " \t\n");
299 /* Magic machine types. Pretty convenient. */
300 temp_var = bind_variable ("HOSTTYPE", HOSTTYPE);
301 set_auto_export (temp_var);
302 temp_var = bind_variable ("OSTYPE", OSTYPE);
303 set_auto_export (temp_var);
304 temp_var = bind_variable ("MACHTYPE", MACHTYPE);
305 set_auto_export (temp_var);
306 temp_var = bind_variable ("HOSTNAME", current_host_name);
307 set_auto_export (temp_var);
309 /* Default MAILCHECK for interactive shells. Defer the creation of a
310 default MAILPATH until the startup files are read, because MAIL
311 names a mail file if MAILCHECK is not set, and we should provide a
312 default only if neither is set. */
313 if (interactive_shell)
314 set_if_not ("MAILCHECK", "60");
316 /* Do some things with shell level. */
317 initialize_shell_level ();
321 /* Initialize the `getopts' stuff. */
322 bind_variable ("OPTIND", "1");
324 bind_variable ("OPTERR", "1");
327 if (login_shell == 1)
330 /* Get the full pathname to THIS shell, and set the BASH variable
332 name = get_bash_name ();
333 temp_var = bind_variable ("BASH", name);
336 /* Make the exported environment variable SHELL be the user's login
337 shell. Note that the `tset' command looks at this variable
338 to determine what style of commands to output; if it ends in "csh",
339 then C-shell commands are output, else Bourne shell commands. */
342 /* Make a variable called BASH_VERSION which contains the version info. */
343 bind_variable ("BASH_VERSION", shell_version_string ());
344 #if defined (ARRAY_VARS)
348 /* Find out if we're supposed to be in Posix.2 mode via an
349 environment variable. */
350 temp_var = find_variable ("POSIXLY_CORRECT");
352 temp_var = find_variable ("POSIX_PEDANTIC");
353 if (temp_var && imported_p (temp_var))
354 sv_strict_posix (temp_var->name);
356 #if defined (HISTORY)
357 /* Set history variables to defaults, and then do whatever we would
358 do if the variable had just been set. Do this only in the case
359 that we are remembering commands on the history list. */
360 if (remember_on_history)
362 name = bash_tilde_expand (posixly_correct ? "~/.sh_history" : "~/.bash_history");
364 set_if_not ("HISTFILE", name);
367 set_if_not ("HISTSIZE", "500");
368 sv_histsize ("HISTSIZE");
372 /* Seed the random number generator. */
373 sbrand (dollar_dollar_pid + (long)shell_start_time);
375 /* Handle some "special" variables that we may have inherited from a
377 if (interactive_shell)
379 temp_var = find_variable ("IGNOREEOF");
381 temp_var = find_variable ("ignoreeof");
382 if (temp_var && imported_p (temp_var))
383 sv_ignoreeof (temp_var->name);
386 #if defined (HISTORY)
387 if (interactive_shell && remember_on_history)
389 sv_history_control ("HISTCONTROL");
390 sv_histignore ("HISTIGNORE");
394 /* Get the user's real and effective user ids. */
397 /* Initialize the dynamic variables, and seed their values. */
398 initialize_dynamic_variables ();
401 /* Set $HOME to the information in the password file if we didn't get
402 it from the environment. */
404 /* This function is not static so the tilde and readline libraries can
409 if (current_user.home_dir == 0)
410 get_current_user_info ();
411 return current_user.home_dir;
419 temp_var = find_variable ("HOME");
421 temp_var = bind_variable ("HOME", get_home_dir ());
422 temp_var->attributes |= att_exported;
425 /* Set $SHELL to the user's login shell if it is not already set. Call
426 get_current_user_info if we haven't already fetched the shell. */
432 temp_var = find_variable ("SHELL");
435 if (current_user.shell == 0)
436 get_current_user_info ();
437 temp_var = bind_variable ("SHELL", current_user.shell);
439 temp_var->attributes |= att_exported;
447 if ((login_shell == 1) && (*shell_name != '/'))
449 if (current_user.shell == 0)
450 get_current_user_info ();
451 name = savestring (current_user.shell);
453 else if (*shell_name == '/')
454 name = savestring (shell_name);
455 else if (shell_name[0] == '.' && shell_name[1] == '/')
457 /* Fast path for common case. */
461 cdir = get_string_value ("PWD");
463 name = xmalloc (len + strlen (shell_name) + 1);
465 strcpy (name + len, shell_name + 1);
472 tname = find_user_command (shell_name);
476 /* Try the current directory. If there is not an executable
477 there, just punt and use the login shell. */
478 s = file_status (shell_name);
481 tname = make_absolute (shell_name, get_string_value ("PWD"));
482 if (*shell_name == '.')
484 name = canonicalize_pathname (tname);
495 if (current_user.shell == 0)
496 get_current_user_info ();
497 name = savestring (current_user.shell);
502 name = full_pathname (tname);
511 adjust_shell_level (change)
514 char new_level[5], *old_SHLVL;
518 old_SHLVL = get_string_value ("SHLVL");
519 old_level = old_SHLVL ? atoi (old_SHLVL) : 0;
521 shell_level = old_level + change;
524 else if (shell_level > 1000)
526 internal_warning ("shell level (%d) too high, resetting to 1", shell_level);
530 /* We don't need the full generality of itos here. */
531 if (shell_level < 10)
533 new_level[0] = shell_level + '0';
536 else if (shell_level < 100)
538 new_level[0] = (shell_level / 10) + '0';
539 new_level[1] = (shell_level % 10) + '0';
542 else if (shell_level < 1000)
544 new_level[0] = (shell_level / 100) + '0';
545 old_level = shell_level % 100;
546 new_level[1] = (old_level / 10) + '0';
547 new_level[2] = (old_level % 10) + '0';
551 temp_var = bind_variable ("SHLVL", new_level);
552 set_auto_export (temp_var);
556 initialize_shell_level ()
561 temp_var = set_if_not ("SHLVL", "0");
562 set_auto_export (temp_var);
564 adjust_shell_level (1);
567 /* Make a variable $PPID, which holds the pid of the shell's parent. */
571 char namebuf[32], *name;
574 name = inttostr ((int) getppid (), namebuf, sizeof(namebuf));
575 temp_var = find_variable ("PPID");
577 temp_var->attributes &= ~(att_readonly | att_exported);
578 temp_var = bind_variable ("PPID", name);
579 temp_var->attributes |= (att_readonly | att_integer);
586 register SHELL_VAR *v;
588 b = inttostr (current_user.uid, buff, sizeof (buff));
589 v = find_variable ("UID");
591 v->attributes &= ~att_readonly;
593 v = bind_variable ("UID", b);
594 v->attributes |= (att_readonly | att_integer);
596 if (current_user.euid != current_user.uid)
597 b = inttostr (current_user.euid, buff, sizeof (buff));
599 v = find_variable ("EUID");
601 v->attributes &= ~att_readonly;
603 v = bind_variable ("EUID", b);
604 v->attributes |= (att_readonly | att_integer);
607 #if defined (ARRAY_VARS)
615 makunbound ("BASH_VERSINFO", shell_variables);
617 vv = make_new_array_variable ("BASH_VERSINFO");
618 av = array_cell (vv);
619 strcpy (d, dist_version);
623 array_add_element (av, 0, d);
624 array_add_element (av, 1, s);
625 s = inttostr (patch_level, d, sizeof (d));
626 array_add_element (av, 2, s);
627 s = inttostr (build_version, d, sizeof (d));
628 array_add_element (av, 3, s);
629 array_add_element (av, 4, release_status);
630 array_add_element (av, 5, MACHTYPE);
632 vv->attributes |= att_readonly;
634 #endif /* ARRAY_VARS */
636 /* Set the environment variables $LINES and $COLUMNS in response to
637 a window size change. */
639 set_lines_and_columns (lines, cols)
644 v = inttostr (lines, val, sizeof (val));
645 bind_variable ("LINES", v);
647 v = inttostr (cols, val, sizeof (val));
648 bind_variable ("COLUMNS", v);
651 /* Set NAME to VALUE if NAME has no value. */
653 set_if_not (name, value)
658 v = find_variable (name);
660 v = bind_variable (name, value);
664 /* Map FUNCTION over the variables in VARIABLES. Return an array of the
665 variables for which FUNCTION returns a non-zero value. A NULL value
666 for FUNCTION means to use all variables. */
668 map_over (function, var_hash_table)
670 HASH_TABLE* var_hash_table;
673 register BUCKET_CONTENTS *tlist;
674 SHELL_VAR *var, **list;
675 int list_index, list_size;
677 list = (SHELL_VAR **)NULL;
678 for (i = list_index = list_size = 0; i < var_hash_table->nbuckets; i++)
680 tlist = get_hash_bucket (i, var_hash_table);
684 var = (SHELL_VAR *)tlist->data;
686 if (!function || (*function) (var))
688 if (list_index + 1 >= list_size)
689 list = (SHELL_VAR **)
690 xrealloc (list, (list_size += 20) * sizeof (SHELL_VAR *));
692 list[list_index++] = var;
693 list[list_index] = (SHELL_VAR *)NULL;
702 sort_variables (array)
705 qsort (array, array_len ((char **)array), sizeof (SHELL_VAR *), qsort_var_comp);
709 qsort_var_comp (var1, var2)
710 SHELL_VAR **var1, **var2;
714 if ((result = (*var1)->name[0] - (*var2)->name[0]) == 0)
715 result = strcmp ((*var1)->name, (*var2)->name);
720 /* Create a NULL terminated array of all the shell variables in TABLE. */
727 list = map_over ((Function *)NULL, table);
728 if (list /* && posixly_correct */)
729 sort_variables (list);
733 /* Create a NULL terminated array of all the shell variables. */
735 all_shell_variables ()
737 return (all_vars (shell_variables));
740 /* Create a NULL terminated array of all the shell functions. */
742 all_shell_functions ()
744 return (all_vars (shell_functions));
747 /* Print VARS to stdout in such a way that they can be read back in. */
749 print_var_list (list)
750 register SHELL_VAR **list;
753 register SHELL_VAR *var;
755 for (i = 0; list && (var = list[i]); i++)
756 if (!invisible_p (var))
757 print_assignment (var);
761 /* Print LIST (a linked list of shell variables) to stdout
762 by printing the names, without the values. Used to support the
765 print_vars_no_values (list)
766 register SHELL_VAR **list;
769 register SHELL_VAR *var;
771 for (i = 0; list && (var = list[i]); i++)
772 if (!invisible_p (var))
773 printf ("%s\n", var->name);
777 /* Print the value of a single SHELL_VAR. No newline is
778 output, but the variable is printed in such a way that
779 it can be read back in. */
781 print_assignment (var)
784 if (function_p (var) && var->value)
786 printf ("%s=", var->name);
787 print_var_function (var);
790 #if defined (ARRAY_VARS)
791 else if (array_p (var) && var->value)
792 print_array_assignment (var, 0);
793 #endif /* ARRAY_VARS */
796 printf ("%s=", var->name);
797 print_var_value (var, 1);
802 /* Print the value cell of VAR, a shell variable. Do not print
803 the name, nor leading/trailing newline. If QUOTE is non-zero,
804 and the value contains shell metacharacters, quote the value
805 in such a way that it can be read back in. */
807 print_var_value (var, quote)
815 if (quote && contains_shell_metas (var->value))
817 t = single_quote (var->value);
822 printf ("%s", var->value);
826 /* Print the function cell of VAR, a shell variable. Do not
827 print the name, nor leading/trailing newline. */
829 print_var_function (var)
832 if (function_p (var) && var->value)
833 printf ("%s", named_function_string ((char *)NULL, function_cell(var), 1));
836 #if defined (ARRAY_VARS)
838 print_array_assignment (var, quoted)
845 vstr = quoted_array_assignment_string (array_cell (var));
847 vstr = array_to_assignment_string (array_cell (var));
850 printf ("%s=%s\n", var->name, quoted ? "'()'" : "()");
853 printf ("%s=%s\n", var->name, vstr);
857 #endif /* ARRAY_VARS */
859 /* **************************************************************** */
861 /* Dynamic Variable Extension */
863 /* **************************************************************** */
867 These are variables whose values are generated anew each time they are
868 referenced. These are implemented using a pair of function pointers
869 in the struct variable: assign_func, which is called from bind_variable,
870 and dynamic_value, which is called from find_variable.
872 assign_func is called from bind_variable, if bind_variable discovers
873 that the variable being assigned to has such a function. The function
875 SHELL_VAR *temp = (*(entry->assign_func)) (entry, value)
876 and the (SHELL_VAR *)temp is returned as the value of bind_variable. It
877 is usually ENTRY (self).
879 dynamic_value is called from find_variable to return a `new' value for
880 the specified dynamic varible. If this function is NULL, the variable
881 is treated as a `normal' shell variable. If it is not, however, then
882 this function is called like this:
883 tempvar = (*(var->dynamic_value)) (var);
885 Sometimes `tempvar' will replace the value of `var'. Other times, the
886 shell will simply use the string value. Pretty object-oriented, huh?
888 Be warned, though: if you `unset' a special variable, it loses its
889 special meaning, even if you subsequently set it.
891 The special assignment code would probably have been better put in
892 subst.c: do_assignment, in the same style as
893 stupidly_hack_special_variables, but I wanted the changes as
894 localized as possible. */
896 /* The value of $SECONDS. This is the number of seconds since shell
897 invocation, or, the number of seconds since the last assignment + the
898 value of the last assignment. */
899 static long seconds_value_assigned;
902 assign_seconds (self, value)
906 seconds_value_assigned = strtol (value, (char **)NULL, 10);
907 shell_start_time = NOW;
915 time_t time_since_start;
918 time_since_start = NOW - shell_start_time;
919 p = itos((int) seconds_value_assigned + time_since_start);
923 var->attributes |= att_integer;
928 /* The random number seed. You can change this by setting RANDOM. */
929 static unsigned long rseed = 1;
930 static unsigned long last_random_value;
932 /* A linear congruential random number generator based on the ANSI
933 C standard. This one isn't very good (the values are alternately
934 odd and even, for example), but a more complicated one is overkill. */
936 /* Returns a pseudo-random number between 0 and 32767. */
940 rseed = rseed * 1103515245 + 12345;
941 return ((unsigned int)(rseed & 32767)); /* was % 32768 */
944 /* Set the random number generator seed to SEED. */
950 last_random_value = 0;
954 assign_random (self, value)
958 sbrand (atoi (value));
969 /* Reset for command and process substitution. */
970 if (subshell_environment)
971 sbrand (rseed + (int)(getpid() + NOW));
975 while (rv == (int)last_random_value);
977 last_random_value = rv;
982 var->attributes |= att_integer;
987 /* Function which returns the current line number. */
995 ln = executing_line_number ();
1003 assign_lineno (var, value)
1007 line_number = atoi (value);
1011 #if defined (HISTORY)
1018 p = itos (history_number ());
1025 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1033 l = get_directory_stack ();
1034 a = word_list_to_array (l);
1035 dispose_array (array_cell (self));
1037 self->value = (char *)a;
1042 assign_dirstack (self, ind, value)
1047 set_dirstack_element (ind, 1, value);
1050 #endif /* PUSHD AND POPD && ARRAY_VARS */
1052 #if defined (ARRAY_VARS)
1053 /* We don't want to initialize the group set with a call to getgroups()
1054 unless we're asked to, but we only want to do it once. */
1062 static char **group_set = (char **)NULL;
1066 group_set = get_group_list (&ng);
1067 a = array_cell (self);
1068 for (i = 0; i < ng; i++)
1069 array_add_element (a, i, group_set[i]);
1073 #endif /* ARRAY_VARS */
1076 initialize_dynamic_variables ()
1080 v = bind_variable ("SECONDS", (char *)NULL);
1081 v->dynamic_value = get_seconds;
1082 v->assign_func = assign_seconds;
1084 v = bind_variable ("RANDOM", (char *)NULL);
1085 v->dynamic_value = get_random;
1086 v->assign_func = assign_random;
1088 v = bind_variable ("LINENO", (char *)NULL);
1089 v->dynamic_value = get_lineno;
1090 v->assign_func = assign_lineno;
1092 #if defined (HISTORY)
1093 v = bind_variable ("HISTCMD", (char *)NULL);
1094 v->dynamic_value = get_histcmd;
1095 v->assign_func = (DYNAMIC_FUNC *)NULL;
1098 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1099 v = make_new_array_variable ("DIRSTACK");
1100 v->dynamic_value = get_dirstack;
1101 v->assign_func = assign_dirstack;
1102 #endif /* PUSHD_AND_POPD && ARRAY_VARS */
1104 #if defined (ARRAY_VARS)
1105 v = make_new_array_variable ("GROUPS");
1106 v->dynamic_value = get_groupset;
1107 v->assign_func = (DYNAMIC_FUNC *)NULL;
1108 v->attributes |= att_readonly;
1112 /* How to get a pointer to the shell variable or function named NAME.
1113 HASHED_VARS is a pointer to the hash table containing the list
1114 of interest (either variables or functions). */
1116 var_lookup (name, hashed_vars)
1118 HASH_TABLE *hashed_vars;
1120 BUCKET_CONTENTS *bucket;
1122 bucket = find_hash_item (name, hashed_vars);
1123 return (bucket ? (SHELL_VAR *)bucket->data : (SHELL_VAR *)NULL);
1126 /* Look up the variable entry named NAME. If SEARCH_TEMPENV is non-zero,
1127 then also search the temporarily built list of exported variables. */
1129 find_variable_internal (name, search_tempenv)
1133 SHELL_VAR *var = (SHELL_VAR *)NULL;
1135 /* If explicitly requested, first look in the temporary environment for
1136 the variable. This allows constructs such as "foo=x eval 'echo $foo'"
1137 to get the `exported' value of $foo. This happens if we are executing
1138 a function or builtin, or if we are looking up a variable in a
1139 "subshell environment". */
1140 if ((search_tempenv || subshell_environment) &&
1141 (temporary_env || builtin_env || function_env))
1142 var = find_tempenv_variable (name);
1145 var = var_lookup (name, shell_variables);
1148 return ((SHELL_VAR *)NULL);
1150 return (var->dynamic_value ? (*(var->dynamic_value)) (var) : var);
1153 /* Look up the variable entry named NAME. Returns the entry or NULL. */
1155 find_variable (name)
1158 return (find_variable_internal
1159 (name, (variable_context || this_shell_builtin || builtin_env)));
1162 /* Look up the function entry whose name matches STRING.
1163 Returns the entry or NULL. */
1165 find_function (name)
1168 return (var_lookup (name, shell_functions));
1171 /* Return the string value of a variable. Return NULL if the variable
1172 doesn't exist, or only has a function as a value. Don't cons a new
1173 string. This is a potential memory leak if the variable is found
1174 in the temporary environment. */
1176 get_string_value (var_name)
1181 var = find_variable (var_name);
1184 return (char *)NULL;
1185 #if defined (ARRAY_VARS)
1186 else if (array_p (var))
1187 return (array_reference (array_cell (var), 0));
1190 return (var->value);
1193 /* This is present for use by the tilde and readline libraries. */
1198 return get_string_value (v);
1201 /* Create a local variable referenced by NAME. */
1203 make_local_variable (name)
1206 SHELL_VAR *new_var, *old_var;
1207 BUCKET_CONTENTS *elt;
1209 /* local foo; local foo; is a no-op. */
1210 old_var = find_variable (name);
1211 if (old_var && old_var->context == variable_context)
1214 elt = remove_hash_item (name, shell_variables);
1217 old_var = (SHELL_VAR *)elt->data;
1222 old_var = (SHELL_VAR *)NULL;
1224 /* If a variable does not already exist with this name, then
1225 just make a new one. */
1227 new_var = bind_variable (name, "");
1230 new_var = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1232 new_var->name = savestring (name);
1233 new_var->value = xmalloc (1);
1234 new_var->value[0] = '\0';
1236 new_var->dynamic_value = (DYNAMIC_FUNC *)NULL;
1237 new_var->assign_func = (DYNAMIC_FUNC *)NULL;
1239 new_var->attributes = exported_p (old_var) ? att_exported : 0;
1241 new_var->prev_context = old_var;
1242 elt = add_hash_item (savestring (name), shell_variables);
1243 elt->data = (char *)new_var;
1246 new_var->context = variable_context;
1247 new_var->attributes |= att_local;
1250 if (variable_context >= local_variable_stack_size)
1252 int old_size = local_variable_stack_size;
1253 RESIZE_MALLOCED_BUFFER (have_local_variables, variable_context, 1,
1254 local_variable_stack_size, 8);
1255 bzero ((char *)have_local_variables + old_size,
1256 local_variable_stack_size - old_size);
1258 have_local_variables[variable_context] = 1; /* XXX */
1263 #if defined (ARRAY_VARS)
1265 make_local_array_variable (name)
1271 var = make_local_variable (name);
1272 array = new_array ();
1274 FREE (value_cell(var));
1275 var->value = (char *)array;
1276 var->attributes |= att_array;
1279 #endif /* ARRAY_VARS */
1281 /* Create a new shell variable with name NAME and add it to the hash table
1282 of shell variables. */
1285 make_new_variable (name)
1289 BUCKET_CONTENTS *elt;
1291 entry = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1293 entry->attributes = 0;
1294 entry->name = savestring (name);
1295 entry->value = (char *)NULL;
1297 entry->dynamic_value = (DYNAMIC_FUNC *)NULL;
1298 entry->assign_func = (DYNAMIC_FUNC *)NULL;
1300 /* Always assume variables are to be made at toplevel!
1301 make_local_variable has the responsibilty of changing the
1302 variable context. */
1304 entry->prev_context = (SHELL_VAR *)NULL;
1306 elt = add_hash_item (savestring (name), shell_variables);
1307 elt->data = (char *)entry;
1312 #if defined (ARRAY_VARS)
1314 make_new_array_variable (name)
1320 entry = make_new_variable (name);
1321 array = new_array ();
1322 entry->value = (char *)array;
1323 entry->attributes |= att_array;
1329 make_variable_value (var, value)
1337 /* If this variable has had its type set to integer (via `declare -i'),
1338 then do expression evaluation on it and store the result. The
1339 functions in expr.c (evalexp and bind_int_variable) are responsible
1340 for turning off the integer flag if they don't want further
1342 if (integer_p (var))
1344 lval = evalexp (value, &expok);
1346 jump_to_top_level (DISCARD);
1347 retval = itos (lval);
1352 retval = savestring (value);
1355 retval = xmalloc (1);
1360 retval = (char *)NULL;
1365 /* Bind a variable NAME to VALUE. This conses up the name
1366 and value strings. */
1368 bind_variable (name, value)
1374 entry = var_lookup (name, shell_variables);
1378 entry = make_new_variable (name);
1379 entry->value = make_variable_value (entry, value);
1381 #if defined (ARRAY_VARS)
1382 else if (entry->assign_func && array_p (entry) == 0)
1384 else if (entry->assign_func)
1386 return ((*(entry->assign_func)) (entry, value));
1389 if (readonly_p (entry))
1391 report_error ("%s: readonly variable", name);
1395 /* Variables which are bound are visible. */
1396 entry->attributes &= ~att_invisible;
1398 newval = make_variable_value (entry, value);
1400 #if defined (ARRAY_VARS)
1401 /* XXX -- this bears looking at again -- XXX */
1402 /* If an existing array variable x is being assigned to with x=b or
1403 `read x' or something of that nature, silently convert it to
1404 x[0]=b or `read x[0]'. */
1405 if (array_p (entry))
1407 array_add_element (array_cell (entry), 0, newval);
1412 FREE (entry->value);
1413 entry->value = newval;
1416 FREE (entry->value);
1417 entry->value = newval;
1421 if (mark_modified_vars)
1422 entry->attributes |= att_exported;
1424 if (exported_p (entry))
1425 array_needs_making = 1;
1430 #if defined (ARRAY_VARS)
1431 /* Convert a shell variable to an array variable. The original value is
1432 saved as array[0]. */
1434 convert_var_to_array (var)
1440 oldval = value_cell (var);
1441 array = new_array ();
1442 array_add_element (array, 0, oldval);
1443 FREE (value_cell (var));
1444 var->value = (char *)array;
1445 var->attributes |= att_array;
1446 var->attributes &= ~att_invisible;
1451 /* Perform an array assignment name[ind]=value. If NAME already exists and
1452 is not an array, and IND is 0, perform name=value instead. If NAME exists
1453 and is not an array, and IND is not 0, convert it into an array with the
1454 existing value as name[0].
1456 If NAME does not exist, just create an array variable, no matter what
1457 IND's value may be. */
1459 bind_array_variable (name, ind, value)
1467 entry = var_lookup (name, shell_variables);
1469 if (entry == (SHELL_VAR *) 0)
1470 entry = make_new_array_variable (name);
1471 else if (readonly_p (entry))
1473 report_error ("%s: readonly variable", name);
1476 else if (array_p (entry) == 0)
1477 entry = convert_var_to_array (entry);
1479 /* ENTRY is an array variable, and ARRAY points to the value. */
1480 newval = make_variable_value (entry, value);
1481 if (entry->assign_func)
1482 (*entry->assign_func) (entry, ind, newval);
1484 array_add_element (array_cell (entry), ind, newval);
1490 /* Perform a compound assignment statement for array NAME, where VALUE is
1491 the text between the parens: NAME=( VALUE ) */
1493 assign_array_from_string (name, value)
1498 var = find_variable (name);
1500 var = make_new_array_variable (name);
1501 else if (readonly_p (var))
1503 report_error ("%s: readonly variable", name);
1504 return ((SHELL_VAR *)NULL);
1506 else if (array_p (var) == 0)
1507 var = convert_var_to_array (var);
1509 return (assign_array_var_from_string (var, value));
1513 assign_array_var_from_word_list (var, list)
1518 register WORD_LIST *l;
1521 for (a = array_cell (var), l = list, i = 0; l; l = l->next, i++)
1522 if (var->assign_func)
1523 (*var->assign_func) (var, i, l->word->word);
1525 array_add_element (a, i, l->word->word);
1529 /* Perform a compound array assignment: VAR->name=( VALUE ). The
1530 VALUE has already had the parentheses stripped. */
1532 assign_array_var_from_string (var, value)
1537 WORD_LIST *list, *nlist;
1538 char *w, *val, *nval;
1539 int ni, len, ind, last_ind;
1544 /* If this is called from declare_builtin, value[0] == '(' and
1545 strchr(value, ')') != 0. In this case, we need to extract
1546 the value from between the parens before going on. */
1547 if (*value == '(') /*)*/
1550 val = extract_array_assignment_list (value, &ni);
1557 /* Expand the value string into a list of words, performing all the
1558 shell expansions including pathname generation and word splitting. */
1559 /* First we split the string on whitespace, using the shell parser
1560 (ksh93 seems to do this). */
1561 list = parse_string_to_word_list (val, "array assign");
1562 /* Now that we've split it, perform the shell expansions on each
1563 word in the list. */
1565 nlist = list ? expand_words_shellexp (list) : (WORD_LIST *)NULL;
1567 nlist = list ? expand_words_no_vars (list) : (WORD_LIST *)NULL;
1570 dispose_words (list);
1575 a = array_cell (var);
1577 /* Now that we are ready to assign values to the array, kill the existing
1582 for (last_ind = 0, list = nlist; list; list = list->next)
1584 w = list->word->word;
1586 /* We have a word of the form [ind]=value */
1589 len = skipsubscript (w, 0);
1591 if (w[len] != ']' || w[len+1] != '=')
1593 nval = make_variable_value (var, w);
1594 if (var->assign_func)
1595 (*var->assign_func) (var, last_ind, nval);
1597 array_add_element (a, last_ind, nval);
1605 report_error ("%s: bad array subscript", w);
1609 if (ALL_ELEMENT_SUB (w[1]) && len == 2)
1611 report_error ("%s: cannot assign to non-numeric index", w);
1615 ind = array_expand_index (w + 1, len);
1618 report_error ("%s: bad array subscript", w);
1624 else /* No [ind]=value, just a stray `=' */
1630 if (integer_p (var))
1631 this_command_name = (char *)NULL; /* no command name for errors */
1632 nval = make_variable_value (var, val);
1633 if (var->assign_func)
1634 (*var->assign_func) (var, ind, nval);
1636 array_add_element (a, ind, nval);
1641 dispose_words (nlist);
1644 #endif /* ARRAY_VARS */
1646 /* Dispose of the information attached to VAR. */
1648 dispose_variable (var)
1654 if (function_p (var))
1655 dispose_command (function_cell (var));
1656 #if defined (ARRAY_VARS)
1657 else if (array_p (var))
1658 dispose_array (array_cell (var));
1661 FREE (value_cell (var));
1665 if (exported_p (var))
1666 array_needs_making = 1;
1671 #if defined (ARRAY_VARS)
1672 /* This function is called with SUB pointing to just after the beginning
1673 `[' of an array subscript. */
1675 unbind_array_element (var, sub)
1682 len = skipsubscript (sub, 0);
1683 if (sub[len] != ']' || len == 0)
1685 builtin_error ("%s[%s: bad array subscript", var->name, sub);
1690 if (ALL_ELEMENT_SUB (sub[0]) && sub[1] == 0)
1692 makunbound (var->name, shell_variables);
1695 ind = array_expand_index (sub, len+1);
1698 builtin_error ("[%s]: bad array subscript", sub);
1701 ae = array_delete_element (array_cell (var), ind);
1703 destroy_array_element (ae);
1708 /* Unset the variable referenced by NAME. */
1710 unbind_variable (name)
1715 var = find_variable (name);
1719 /* This function should never be called with an array variable name. */
1720 #if defined (ARRAY_VARS)
1721 if (array_p (var) == 0 && var->value)
1727 var->value = (char *)NULL;
1730 makunbound (name, shell_variables);
1735 /* Make the variable associated with NAME go away. HASH_LIST is the
1736 hash table from which this variable should be deleted (either
1737 shell_variables or shell_functions).
1738 Returns non-zero if the variable couldn't be found. */
1740 makunbound (name, hash_list)
1742 HASH_TABLE *hash_list;
1744 BUCKET_CONTENTS *elt, *new_elt;
1745 SHELL_VAR *old_var, *new_var;
1748 elt = remove_hash_item (name, hash_list);
1753 old_var = (SHELL_VAR *)elt->data;
1754 new_var = old_var->prev_context;
1756 if (old_var && exported_p (old_var))
1757 array_needs_making++;
1759 /* If we're unsetting a local variable and we're still executing inside
1760 the function, just mark the variable as invisible.
1761 kill_all_local_variables will clean it up later. This must be done
1762 so that if the variable is subsequently assigned a new value inside
1763 the function, the `local' attribute is still present. We also need
1764 to add it back into the correct hash table. */
1765 if (old_var && local_p (old_var) && variable_context == old_var->context)
1767 old_var->attributes |= att_invisible;
1768 new_elt = add_hash_item (savestring (old_var->name), hash_list);
1769 new_elt->data = (char *)old_var;
1770 stupidly_hack_special_variables (old_var->name);
1778 /* Has to be a variable, functions don't have previous contexts. */
1779 new_elt = add_hash_item (savestring (new_var->name), hash_list);
1780 new_elt->data = (char *)new_var;
1782 if (exported_p (new_var))
1783 set_auto_export (new_var);
1786 /* Have to save a copy of name here, because it might refer to
1787 old_var->name. If so, stupidly_hack_special_variables will
1788 reference freed memory. */
1789 t = savestring (name);
1794 dispose_variable (old_var);
1795 stupidly_hack_special_variables (t);
1800 #ifdef INCLUDE_UNUSED
1801 /* Remove the variable with NAME if it is a local variable in the
1804 kill_local_variable (name)
1809 temp = find_variable (name);
1810 if (temp && temp->context == variable_context)
1812 makunbound (name, shell_variables);
1819 /* Get rid of all of the variables in the current context. */
1821 variable_in_context (var)
1824 return (var && var->context == variable_context);
1828 kill_all_local_variables ()
1830 register int i, pass;
1831 register SHELL_VAR *var, **list;
1832 HASH_TABLE *varlist;
1834 /* If HAVE_LOCAL_VARIABLES == 0, it means that we don't have any local
1835 variables at all. If VARIABLE_CONTEXT >= LOCAL_VARIABLE_STACK_SIZE,
1836 it means that we have some local variables, but not in this variable
1837 context (level of function nesting). Also, if
1838 HAVE_LOCAL_VARIABLES[VARIABLE_CONTEXT] == 0, we have no local variables
1840 if (have_local_variables == 0 ||
1841 variable_context >= local_variable_stack_size ||
1842 have_local_variables[variable_context] == 0)
1845 for (pass = 0; pass < 2; pass++)
1847 varlist = pass ? shell_functions : shell_variables;
1849 list = map_over (variable_in_context, varlist);
1853 for (i = 0; var = list[i]; i++)
1855 var->attributes &= ~att_local;
1856 makunbound (var->name, varlist);
1862 have_local_variables[variable_context] = 0; /* XXX */
1866 free_variable_hash_data (data)
1869 SHELL_VAR *var, *prev;
1871 var = (SHELL_VAR *)data;
1874 prev = var->prev_context;
1875 dispose_variable (var);
1880 /* Delete the entire contents of the hash table. */
1882 delete_all_variables (hashed_vars)
1883 HASH_TABLE *hashed_vars;
1885 flush_hash_table (hashed_vars, free_variable_hash_data);
1889 new_shell_variable (name)
1894 var = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1896 bzero ((char *)var, sizeof (SHELL_VAR));
1897 var->name = savestring (name);
1901 /* Do a function binding to a variable. You pass the name and
1902 the command to bind to. This conses the name and command. */
1904 bind_function (name, value)
1910 entry = find_function (name);
1913 BUCKET_CONTENTS *elt;
1915 elt = add_hash_item (savestring (name), shell_functions);
1917 elt->data = (char *)new_shell_variable (name);
1918 entry = (SHELL_VAR *)elt->data;
1919 entry->dynamic_value = entry->assign_func = (DYNAMIC_FUNC *)NULL;
1921 /* Functions are always made at the top level. This allows a
1922 function to define another function (like autoload). */
1927 dispose_command ((COMMAND *)entry->value);
1929 entry->value = value ? (char *)copy_command (value) : (char *)NULL;
1930 entry->attributes |= att_function;
1932 if (mark_modified_vars)
1933 entry->attributes |= att_exported;
1935 entry->attributes &= ~att_invisible; /* Just to be sure */
1937 if (exported_p (entry))
1938 array_needs_making = 1;
1943 #ifdef INCLUDE_UNUSED
1944 /* Copy VAR to a new data structure and return that structure. */
1949 SHELL_VAR *copy = (SHELL_VAR *)NULL;
1953 copy = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1955 copy->attributes = var->attributes;
1956 copy->name = savestring (var->name);
1958 if (function_p (var))
1959 copy->value = (char *)copy_command (function_cell (var));
1960 #if defined (ARRAY_VARS)
1961 else if (array_p (var))
1962 copy->value = (char *)dup_array (array_cell (var));
1964 else if (value_cell (var))
1965 copy->value = savestring (value_cell (var));
1967 copy->value = (char *)NULL;
1969 copy->dynamic_value = var->dynamic_value;
1970 copy->assign_func = var->assign_func;
1972 copy->context = var->context;
1974 /* Don't bother copying previous contexts along with this variable. */
1975 copy->prev_context = (SHELL_VAR *)NULL;
1981 #define FIND_OR_MAKE_VARIABLE(name, entry) \
1984 entry = find_variable (name); \
1987 entry = bind_variable (name, ""); \
1988 if (!no_invisible_vars) entry->attributes |= att_invisible; \
1993 /* Make the variable associated with NAME be readonly.
1994 If NAME does not exist yet, create it. */
1996 set_var_read_only (name)
2001 FIND_OR_MAKE_VARIABLE (name, entry);
2002 entry->attributes |= att_readonly;
2005 #ifdef INCLUDE_UNUSED
2006 /* Make the function associated with NAME be readonly.
2007 If NAME does not exist, we just punt, like auto_export code below. */
2009 set_func_read_only (name)
2014 entry = find_function (name);
2016 entry->attributes |= att_readonly;
2019 /* Make the variable associated with NAME be auto-exported.
2020 If NAME does not exist yet, create it. */
2022 set_var_auto_export (name)
2027 FIND_OR_MAKE_VARIABLE (name, entry);
2028 set_auto_export (entry);
2031 /* Make the function associated with NAME be auto-exported. */
2033 set_func_auto_export (name)
2038 entry = find_function (name);
2040 set_auto_export (entry);
2044 #if defined (ARRAY_VARS)
2045 /* This function assumes s[i] == '['; returns with s[ret] == ']' if
2046 an array subscript is correctly parsed. */
2048 skipsubscript (s, i)
2054 for (count = 1; count && (c = s[++i]); )
2063 #endif /* ARRAY_VARS */
2065 /* Returns non-zero if STRING is an assignment statement. The returned value
2066 is the index of the `=' sign. */
2071 register int c, newi, indx;
2073 c = string[indx = 0];
2075 if (legal_variable_starter (c) == 0)
2078 while (c = string[indx])
2080 /* The following is safe. Note that '=' at the start of a word
2081 is not an assignment statement. */
2085 #if defined (ARRAY_VARS)
2088 newi = skipsubscript (string, indx);
2089 if (string[newi++] != ']')
2091 return ((string[newi] == '=') ? newi : 0);
2093 #endif /* ARRAY_VARS */
2095 /* Variable names in assignment statements may contain only letters,
2097 if (legal_variable_char (c) == 0)
2111 return (invisible_p (var) == 0);
2115 _visible_names (table)
2120 list = map_over (visible_var, table);
2122 if (list /* && posixly_correct */)
2123 sort_variables (list);
2129 all_visible_variables ()
2131 return (_visible_names (shell_variables));
2135 all_visible_functions ()
2137 return (_visible_names (shell_functions));
2140 #endif /* READLINE */
2142 /* Return non-zero if the variable VAR is visible and exported. Array
2143 variables cannot be exported. */
2145 visible_and_exported (var)
2148 return (invisible_p (var) == 0 && exported_p (var));
2151 /* Make an array of assignment statements from the hash table
2152 HASHED_VARS which contains SHELL_VARs. Only visible, exported
2153 variables are eligible. */
2155 make_var_array (hashed_vars)
2156 HASH_TABLE *hashed_vars;
2158 register int i, list_index;
2159 register SHELL_VAR *var;
2160 char **list, *value;
2163 vars = map_over (visible_and_exported, hashed_vars);
2166 return (char **)NULL;
2168 list = (char **)xmalloc ((1 + array_len ((char **)vars)) * sizeof (char *));
2170 for (i = 0, list_index = 0; var = vars[i]; i++)
2172 if (function_p (var))
2173 value = named_function_string ((char *)NULL, function_cell (var), 0);
2174 #if defined (ARRAY_VARS)
2175 else if (array_p (var))
2177 value = array_to_assignment_string (array_cell (var));
2179 continue; /* XXX array vars cannot yet be exported */
2183 value = value_cell (var);
2187 int name_len, value_len;
2190 name_len = strlen (var->name);
2191 value_len = strlen (value);
2192 p = list[list_index] = xmalloc (2 + name_len + value_len);
2193 strcpy (p, var->name);
2195 strcpy (p + name_len + 1, value);
2197 #if defined (ARRAY_VARS)
2205 list[list_index] = (char *)NULL;
2209 /* Add STRING to the array of foo=bar strings that we already
2210 have to add to the environment. */
2212 assign_in_env (string)
2216 char *name, *temp, *value;
2221 offset = assignment (string);
2222 name = savestring (string);
2223 value = (char *)NULL;
2225 if (name[offset] == '=')
2229 var = find_variable (name);
2230 if (var && readonly_p (var))
2232 report_error ("%s: readonly variable", name);
2236 temp = name + offset + 1;
2237 temp = (strchr (temp, '~') != 0) ? bash_tilde_expand (temp) : savestring (temp);
2239 list = expand_string_unsplit (temp, 0);
2240 value = string_list (list);
2243 dispose_words (list);
2248 nlen = strlen (name);
2249 vlen = value ? strlen (value) : 0;
2250 temp = xmalloc (2 + nlen + vlen);
2251 strcpy (temp, name);
2253 temp[nlen + 1] = '\0';
2257 strcpy (temp + nlen + 1, value);
2262 if (temporary_env == 0)
2264 temporary_env = (char **)xmalloc (sizeof (char *));
2265 temporary_env [0] = (char *)NULL;
2268 size = array_len (temporary_env);
2269 temporary_env = (char **)
2270 xrealloc (temporary_env, (size + 2) * (sizeof (char *)));
2272 temporary_env[size] = temp;
2273 temporary_env[size + 1] = (char *)NULL;
2274 array_needs_making = 1;
2276 if (echo_command_at_execute)
2278 /* The Korn shell prints the `+ ' in front of assignment statements,
2280 fprintf (stderr, "%s%s\n", indirection_level_string (), temp);
2287 /* Search for NAME in ARRAY, an array of strings in the same format as the
2288 environment array (i.e, name=value). If NAME is present, make a new
2289 variable and return it. Otherwise, return NULL. */
2291 find_name_in_env_array (name, array)
2298 return ((SHELL_VAR *)NULL);
2300 for (i = 0, l = strlen (name); array[i]; i++)
2302 if (STREQN (array[i], name, l) && array[i][l] == '=')
2307 /* This is a potential memory leak. The code should really save
2308 the created variables in some auxiliary data structure, which
2309 can be disposed of at the appropriate time. */
2310 temp = new_shell_variable (name);
2311 w = array[i] + l + 1;
2313 temp->value = *w ? savestring (w) : (char *)NULL;
2315 temp->attributes = att_exported|att_tempvar;
2317 temp->prev_context = (SHELL_VAR *)NULL;
2319 temp->dynamic_value = temp->assign_func = (DYNAMIC_FUNC *)NULL;
2324 return ((SHELL_VAR *)NULL);
2327 /* Find a variable in the temporary environment that is named NAME.
2328 The temporary environment can be either the environment provided
2329 to a simple command, or the environment provided to a shell function.
2330 We only search the function environment if we are currently executing
2331 a shell function body (variable_context > 0). Return a consed variable,
2332 or NULL if not found. */
2334 find_tempenv_variable (name)
2339 var = (SHELL_VAR *)NULL;
2342 var = find_name_in_env_array (name, temporary_env);
2344 /* We don't check this_shell_builtin because the command that needs the
2345 value from builtin_env may be a disk command run inside a script run
2346 with `.' and a temporary env. */
2347 if (!var && builtin_env)
2348 var = find_name_in_env_array (name, builtin_env);
2350 if (!var && variable_context && function_env)
2351 var = find_name_in_env_array (name, function_env);
2356 /* Free the storage allocated to the string array pointed to by ARRAYP, and
2357 make that variable have a null pointer as a value. */
2359 dispose_temporary_vars (arrayp)
2365 free_array (*arrayp);
2366 *arrayp = (char **)NULL;
2367 array_needs_making = 1;
2370 /* Free the storage used in the variable array for temporary
2371 environment variables. */
2373 dispose_used_env_vars ()
2375 dispose_temporary_vars (&temporary_env);
2378 /* Free the storage used for temporary environment variables given to
2379 commands when executing inside of a function body. */
2381 dispose_function_env ()
2383 dispose_temporary_vars (&function_env);
2386 /* Free the storage used for temporary environment variables given to
2387 commands when executing a builtin command such as "source". */
2389 dispose_builtin_env ()
2391 dispose_temporary_vars (&builtin_env);
2394 /* Take all of the shell variables in ENV_ARRAY and make shell variables
2395 from them at the current variable context. */
2397 merge_env_array (env_array)
2407 for (i = 0; env_array[i]; i++)
2409 l = assignment (env_array[i]);
2410 name = env_array[i];
2411 val = env_array[i] + l + 1;
2413 temp = bind_variable (name, val);
2419 merge_temporary_env ()
2421 merge_env_array (temporary_env);
2425 merge_builtin_env ()
2427 merge_env_array (builtin_env);
2430 /* Add ENVSTR to the end of the exported environment, EXPORT_ENV. */
2431 #define add_to_export_env(envstr,do_alloc) \
2434 if (export_env_index >= (export_env_size - 1)) \
2436 export_env_size += 16; \
2437 export_env = (char **)xrealloc (export_env, export_env_size * sizeof (char *)); \
2439 export_env[export_env_index++] = (do_alloc) ? savestring (envstr) : envstr; \
2440 export_env[export_env_index] = (char *)NULL; \
2443 #define ISFUNCTION(s, o) ((s[o + 1] == '(') && (s[o + 2] == ')'))
2445 /* Add ASSIGN to EXPORT_ENV, or supercede a previous assignment in the
2446 array with the same left-hand side. Return the new EXPORT_ENV. */
2448 add_or_supercede_exported_var (assign, do_alloc)
2455 equal_offset = assignment (assign);
2456 if (equal_offset == 0)
2457 return (export_env);
2459 /* If this is a function, then only supercede the function definition.
2460 We do this by including the `=(' in the comparison. */
2461 if (assign[equal_offset + 1] == '(')
2464 for (i = 0; i < export_env_index; i++)
2466 if (STREQN (assign, export_env[i], equal_offset + 1))
2468 free (export_env[i]);
2469 export_env[i] = do_alloc ? savestring (assign) : assign;
2470 return (export_env);
2473 add_to_export_env (assign, do_alloc);
2474 return (export_env);
2477 /* Make the environment array for the command about to be executed, if the
2478 array needs making. Otherwise, do nothing. If a shell action could
2479 change the array that commands receive for their environment, then the
2480 code should `array_needs_making++'. */
2482 maybe_make_export_env ()
2485 register char **temp_array;
2488 if (array_needs_making)
2491 free_array_members (export_env);
2493 /* Make a guess based on how many shell variables and functions we
2494 have. Since there will always be array variables, and array
2495 variables are not (yet) exported, this will always be big enough
2496 for the exported variables and functions, without any temporary
2497 or function environments. */
2498 new_size = shell_variables->nentries + shell_functions->nentries + 1;
2499 if (new_size > export_env_size)
2501 export_env_size = new_size;
2502 export_env = (char **)xrealloc (export_env, export_env_size * sizeof (char *));
2504 export_env[export_env_index = 0] = (char *)NULL;
2506 temp_array = make_var_array (shell_variables);
2509 for (i = 0; temp_array[i]; i++)
2510 add_to_export_env (temp_array[i], 0);
2514 temp_array = make_var_array (shell_functions);
2517 for (i = 0; temp_array[i]; i++)
2518 add_to_export_env (temp_array[i], 0);
2523 for (i = 0; function_env[i]; i++)
2524 export_env = add_or_supercede_exported_var (function_env[i], 1);
2527 for (i = 0; temporary_env[i]; i++)
2528 export_env = add_or_supercede_exported_var (temporary_env[i], 1);
2531 /* If we changed the array, then sort it alphabetically. */
2532 if (posixly_correct == 0 && (temporary_env || function_env))
2533 sort_char_array (export_env);
2536 array_needs_making = 0;
2540 /* This is an efficiency hack. PWD and OLDPWD are auto-exported, so
2541 we will need to remake the exported environment every time we
2542 change directories. `_' is always put into the environment for
2543 every external command, so without special treatment it will always
2544 cause the environment to be remade.
2546 If there is no other reason to make the exported environment, we can
2547 just update the variables in place and mark the exported environment
2548 as no longer needing a remake. */
2550 update_export_env_inplace (env_prefix, preflen, value)
2557 evar = xmalloc (STRLEN (value) + preflen + 1);
2558 strcpy (evar, env_prefix);
2560 strcpy (evar + preflen, value);
2561 export_env = add_or_supercede_exported_var (evar, 0);
2564 /* We always put _ in the environment as the name of this command. */
2566 put_command_name_into_env (command_name)
2569 update_export_env_inplace ("_=", 2, command_name);
2572 #if 0 /* UNUSED -- it caused too many problems */
2574 put_gnu_argv_flags_into_env (pid, flags_string)
2584 fl = strlen (flags_string);
2586 dummy = xmalloc (l + fl + 30);
2588 strcpy (dummy + 1, pbuf);
2589 strcpy (dummy + 1 + l, "_GNU_nonoption_argv_flags_");
2590 dummy[l + 27] = '=';
2591 strcpy (dummy + l + 28, flags_string);
2595 export_env = add_or_supercede_exported_var (dummy, 0);
2599 /* Return a string denoting what our indirection level is. */
2600 static char indirection_string[100];
2603 indirection_level_string ()
2608 indirection_string[0] = '\0';
2609 ps4 = get_string_value ("PS4");
2611 if (ps4 == 0 || *ps4 == '\0')
2612 return (indirection_string);
2614 ps4 = decode_prompt_string (ps4);
2616 for (i = 0; *ps4 && i < indirection_level && i < 99; i++)
2617 indirection_string[i] = *ps4;
2619 for (j = 1; *ps4 && ps4[j] && i < 99; i++, j++)
2620 indirection_string[i] = ps4[j];
2622 indirection_string[i] = '\0';
2624 return (indirection_string);
2627 /*************************************************
2629 * Functions to manage special variables *
2631 *************************************************/
2633 /* Extern declarations for variables this code has to manage. */
2634 extern int eof_encountered, eof_encountered_limit, ignoreeof;
2636 #if defined (READLINE)
2637 extern int no_line_editing;
2638 extern int hostname_list_initialized;
2641 /* An alist of name.function for each special variable. Most of the
2642 functions don't do much, and in fact, this would be faster with a
2643 switch statement, but by the end of this file, I am sick of switch
2646 #define SET_INT_VAR(name, intvar) intvar = find_variable (name) != 0
2648 struct name_and_function {
2650 VFunction *function;
2651 } special_vars[] = {
2652 { "PATH", sv_path },
2653 { "MAIL", sv_mail },
2654 { "MAILPATH", sv_mail },
2655 { "MAILCHECK", sv_mail },
2657 { "POSIXLY_CORRECT", sv_strict_posix },
2658 { "GLOBIGNORE", sv_globignore },
2660 /* Variables which only do something special when READLINE is defined. */
2661 #if defined (READLINE)
2662 { "TERM", sv_terminal },
2663 { "TERMCAP", sv_terminal },
2664 { "TERMINFO", sv_terminal },
2665 { "HOSTFILE", sv_hostfile },
2666 #endif /* READLINE */
2668 /* Variables which only do something special when HISTORY is defined. */
2669 #if defined (HISTORY)
2670 { "HISTIGNORE", sv_histignore },
2671 { "HISTSIZE", sv_histsize },
2672 { "HISTFILESIZE", sv_histsize },
2673 { "HISTCONTROL", sv_history_control },
2674 # if defined (BANG_HISTORY)
2675 { "histchars", sv_histchars },
2676 # endif /* BANG_HISTORY */
2677 #endif /* HISTORY */
2679 { "IGNOREEOF", sv_ignoreeof },
2680 { "ignoreeof", sv_ignoreeof },
2682 { "OPTIND", sv_optind },
2683 { "OPTERR", sv_opterr },
2685 { "TEXTDOMAIN", sv_locale },
2686 { "TEXTDOMAINDIR", sv_locale },
2687 { "LC_ALL", sv_locale },
2688 { "LC_COLLATE", sv_locale },
2689 { "LC_CTYPE", sv_locale },
2690 { "LC_MESSAGES", sv_locale },
2691 { "LANG", sv_locale },
2693 #if defined (HAVE_TZSET) && defined (PROMPT_STRING_DECODE)
2697 { (char *)0, (VFunction *)0 }
2700 /* The variable in NAME has just had its state changed. Check to see if it
2701 is one of the special ones where something special happens. */
2703 stupidly_hack_special_variables (name)
2708 for (i = 0; special_vars[i].name; i++)
2710 if (STREQ (special_vars[i].name, name))
2712 (*(special_vars[i].function)) (name);
2718 /* What to do just after the PATH variable has changed. */
2724 flush_hashed_filenames ();
2727 /* What to do just after one of the MAILxxxx variables has changed. NAME
2728 is the name of the variable. This is called with NAME set to one of
2729 MAIL, MAILCHECK, or MAILPATH. */
2734 /* If the time interval for checking the files has changed, then
2735 reset the mail timer. Otherwise, one of the pathname vars
2736 to the users mailbox has changed, so rebuild the array of
2738 if (name[4] == 'C') /* if (strcmp (name, "MAILCHECK") == 0) */
2739 reset_mail_timer ();
2743 remember_mail_dates ();
2747 /* What to do when GLOBIGNORE changes. */
2749 sv_globignore (name)
2752 setup_glob_ignore (name);
2755 #if defined (READLINE)
2756 /* What to do just after one of the TERMxxx variables has changed.
2757 If we are an interactive shell, then try to reset the terminal
2758 information in readline. */
2763 if (interactive_shell && no_line_editing == 0)
2764 rl_reset_terminal (get_string_value ("TERM"));
2771 hostname_list_initialized = 0;
2773 #endif /* READLINE */
2775 #if defined (HISTORY)
2776 /* What to do after the HISTSIZE or HISTFILESIZE variables change.
2777 If there is a value for this HISTSIZE (and it is numeric), then stifle
2778 the history. Otherwise, if there is NO value for this variable,
2779 unstifle the history. If name is HISTFILESIZE, and its value is
2780 numeric, truncate the history file to hold no more than that many
2789 temp = get_string_value (name);
2793 if (legal_number (temp, &num))
2797 stifle_history (num);
2798 num = where_history ();
2799 if (history_lines_this_session > num)
2800 history_lines_this_session = num;
2804 history_truncate_file (get_string_value ("HISTFILE"), (int)num);
2805 if (num <= history_lines_in_file)
2806 history_lines_in_file = num;
2810 else if (name[4] == 'S')
2811 unstifle_history ();
2814 /* What to do after the HISTIGNORE variable changes. */
2816 sv_histignore (name)
2819 setup_history_ignore (name);
2822 /* What to do after the HISTCONTROL variable changes. */
2824 sv_history_control (name)
2829 history_control = 0;
2830 temp = get_string_value (name);
2832 if (temp && *temp && STREQN (temp, "ignore", 6))
2834 if (temp[6] == 's') /* ignorespace */
2835 history_control = 1;
2836 else if (temp[6] == 'd') /* ignoredups */
2837 history_control = 2;
2838 else if (temp[6] == 'b') /* ignoreboth */
2839 history_control = 3;
2843 #if defined (BANG_HISTORY)
2844 /* Setting/unsetting of the history expansion character. */
2851 temp = get_string_value (name);
2854 history_expansion_char = *temp;
2855 if (temp[0] && temp[1])
2857 history_subst_char = temp[1];
2859 history_comment_char = temp[2];
2864 history_expansion_char = '!';
2865 history_subst_char = '^';
2866 history_comment_char = '#';
2869 #endif /* BANG_HISTORY */
2870 #endif /* HISTORY */
2872 #if defined (HAVE_TZSET) && defined (PROMPT_STRING_DECODE)
2881 /* If the variable exists, then the value of it can be the number
2882 of times we actually ignore the EOF. The default is small,
2883 (smaller than csh, anyway). */
2891 eof_encountered = 0;
2893 tmp_var = find_variable (name);
2894 ignoreeof = tmp_var != 0;
2895 temp = tmp_var ? value_cell (tmp_var) : (char *)NULL;
2897 eof_encountered_limit = (*temp && all_digits (temp)) ? atoi (temp) : 10;
2898 set_shellopts (); /* make sure `ignoreeof' is/is not in $SHELLOPTS */
2908 tt = get_string_value ("OPTIND");
2913 /* According to POSIX, setting OPTIND=1 resets the internal state
2915 if (s < 0 || s == 1)
2929 tt = get_string_value ("OPTERR");
2930 sh_opterr = (tt && *tt) ? atoi (tt) : 1;
2934 sv_strict_posix (name)
2937 SET_INT_VAR (name, posixly_correct);
2938 posix_initialize (posixly_correct);
2939 #if defined (READLINE)
2940 if (interactive_shell)
2941 posix_readline_initialize (posixly_correct);
2942 #endif /* READLINE */
2943 set_shellopts (); /* make sure `posix' is/is not in $SHELLOPTS */
2952 v = get_string_value (name);
2953 if (name[0] == 'L' && name[1] == 'A') /* LANG */
2956 set_locale_var (name, v); /* LC_*, TEXTDOMAIN* */
2959 #if defined (ARRAY_VARS)
2961 set_pipestatus_array (ps)
2969 v = find_variable ("PIPESTATUS");
2971 v = make_new_array_variable ("PIPESTATUS");
2972 if (array_p (v) == 0)
2973 return; /* Do nothing if not an array variable. */
2977 for (i = 0; ps[i] != -1; i++)
2979 t = inttostr (ps[i], tbuf, sizeof (tbuf));
2980 array_add_element (a, i, t);
2986 set_pipestatus_from_exit (s)
2989 #if defined (ARRAY_VARS)
2990 static int v[2] = { 0, -1 };
2993 set_pipestatus_array (v);