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 2, 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, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
23 #include "bashtypes.h"
24 #include "posixstat.h"
25 #include "posixtime.h"
31 #if defined (HAVE_UNISTD_H)
36 #include "chartypes.h"
42 #include "execute_cmd.h"
44 #include "mailcheck.h"
49 #include "builtins/getopt.h"
50 #include "builtins/common.h"
52 #if defined (READLINE)
53 # include "bashline.h"
54 # include <readline/readline.h>
56 # include <tilde/tilde.h>
60 # include "bashhist.h"
61 # include <readline/history.h>
64 #if defined (PROGRAMMABLE_COMPLETION)
65 # include "pcomplete.h"
68 /* Variables used here and defined in other files. */
69 extern int posixly_correct;
70 extern int line_number;
71 extern int subshell_environment, indirection_level;
72 extern int build_version, patch_level;
73 extern char *dist_version, *release_status;
74 extern char *shell_name;
75 extern char *primary_prompt, *secondary_prompt;
76 extern char *current_host_name;
77 extern sh_builtin_func_t *this_shell_builtin;
78 extern SHELL_VAR *this_shell_function;
79 extern char *this_command_name;
80 extern time_t shell_start_time;
82 /* The list of shell variables that the user has created, or that came from
84 HASH_TABLE *shell_variables = (HASH_TABLE *)NULL;
86 /* The list of shell functions that the user has created, or that came from
88 HASH_TABLE *shell_functions = (HASH_TABLE *)NULL;
90 /* The current variable context. This is really a count of how deep into
91 executing functions we are. */
92 int variable_context = 0;
94 /* The array of shell assignments which are made only in the environment
95 for a single command. */
96 char **temporary_env = (char **)NULL;
98 /* The array of shell assignments which are in the environment for the
99 execution of a shell function. */
100 char **function_env = (char **)NULL;
102 /* The array of shell assignments which are made only in the environment
103 for the execution of a shell builtin command which may cause more than
104 one command to be executed (e.g., "eval" or "source"). */
105 char **builtin_env = (char **)NULL;
107 /* Some funky variables which are known about specially. Here is where
108 "$*", "$1", and all the cruft is kept. */
109 char *dollar_vars[10];
110 WORD_LIST *rest_of_args = (WORD_LIST *)NULL;
112 /* The value of $$. */
113 pid_t dollar_dollar_pid;
115 /* An array which is passed to commands as their environment. It is
116 manufactured from the union of the initial environment and the
117 shell variables that are marked for export. */
118 char **export_env = (char **)NULL;
119 static int export_env_index;
120 static int export_env_size;
122 /* Non-zero means that we have to remake EXPORT_ENV. */
123 int array_needs_making = 1;
125 /* The number of times BASH has been executed. This is set
126 by initialize_variables (). */
129 static char *have_local_variables;
130 static int local_variable_stack_size;
132 /* Some forward declarations. */
133 static void set_machine_vars __P((void));
134 static void set_home_var __P((void));
135 static void set_shell_var __P((void));
136 static char *get_bash_name __P((void));
137 static void initialize_shell_level __P((void));
138 static void uidset __P((void));
139 #if defined (ARRAY_VARS)
140 static void make_vers_array __P((void));
142 static void initialize_dynamic_variables __P((void));
144 static void sbrand __P((unsigned long)); /* set bash random number generator. */
146 static int qsort_var_comp __P((SHELL_VAR **, SHELL_VAR **));
147 static SHELL_VAR **all_vars __P((HASH_TABLE *));
149 static void free_variable_hash_data __P((PTR_T));
150 static SHELL_VAR *new_shell_variable __P((const char *));
152 static SHELL_VAR *make_new_variable __P((const char *));
154 static int visible_var __P((SHELL_VAR *));
155 static SHELL_VAR **_visible_names __P((HASH_TABLE *));
156 static int visible_and_exported __P((SHELL_VAR *));
157 #if defined (ARRAY_VARS)
158 static int visible_array_vars __P((SHELL_VAR *));
161 static inline char *mk_env_string __P((const char *, const char *));
162 static SHELL_VAR *shell_var_from_env_string __P((const char *, char *, int));
163 static SHELL_VAR *bind_name_in_env_array __P((const char *, char *, char **));
164 static SHELL_VAR *find_name_in_env_array __P((const char *, char **));
166 static SHELL_VAR *bind_tempenv_variable __P((const char *, char *));
167 static void dispose_temporary_vars __P((char ***));
168 static void merge_env_array __P((char **));
170 /* Make VAR be auto-exported. VAR is a pointer to a SHELL_VAR. */
171 #define set_auto_export(var) \
172 do { var->attributes |= att_exported; array_needs_making = 1; } while (0)
174 /* Initialize the shell variables from the current environment.
175 If PRIVMODE is nonzero, don't import functions from ENV or
178 initialize_shell_variables (env, privmode)
182 char *name, *string, *temp_string;
183 int c, char_index, string_index, string_length;
186 if (shell_variables == 0)
187 shell_variables = make_hash_table (0);
189 if (shell_functions == 0)
190 shell_functions = make_hash_table (0);
192 for (string_index = 0; string = env[string_index++]; )
196 while ((c = *string++) && c != '=')
198 if (string[-1] == '=')
199 char_index = string - name - 1;
201 /* If there are weird things in the environment, like `=xxx' or a
202 string without an `=', just skip them. */
206 /* ASSERT(name[char_index] == '=') */
207 name[char_index] = '\0';
208 /* Now, name = env variable name, string = env variable value, and
209 char_index == strlen (name) */
211 /* If exported function, define it now. Don't import functions from
212 the environment in privileged mode. */
213 if (privmode == 0 && read_but_dont_execute == 0 && STREQN ("() {", string, 4))
215 string_length = strlen (string);
216 temp_string = (char *)xmalloc (3 + string_length + char_index);
218 strcpy (temp_string, name);
219 temp_string[char_index] = ' ';
220 strcpy (temp_string + char_index + 1, string);
222 parse_and_execute (temp_string, name, SEVAL_NONINT|SEVAL_NOHIST);
224 /* Ancient backwards compatibility. Old versions of bash exported
225 functions like name()=() {...} */
226 if (name[char_index - 1] == ')' && name[char_index - 2] == '(')
227 name[char_index - 2] = '\0';
229 if (temp_var = find_function (name))
231 VSETATTR (temp_var, (att_exported|att_imported));
232 array_needs_making = 1;
235 report_error ("error importing function definition for `%s'", name);
238 if (name[char_index - 1] == ')' && name[char_index - 2] == '\0')
239 name[char_index - 2] = '('; /* ) */
241 #if defined (ARRAY_VARS)
243 /* Array variables may not yet be exported. */
244 else if (*string == '(' && string[1] == '[' && strchr (string, ')'))
247 temp_string = extract_array_assignment_list (string, &string_length);
248 temp_var = assign_array_from_string (name, temp_string);
250 VSETATTR (temp_var, (att_exported | att_imported));
251 array_needs_making = 1;
257 temp_var = bind_variable (name, string);
258 VSETATTR (temp_var, (att_exported | att_imported));
259 array_needs_making = 1;
262 name[char_index] = '=';
263 /* temp_var can be NULL if it was an exported function with a syntax
264 error (a different bug, but it still shouldn't dump core). */
265 if (temp_var && function_p (temp_var) == 0) /* XXX not yet */
267 CACHE_IMPORTSTR (temp_var, name);
273 /* Set up initial value of $_ */
274 temp_var = bind_variable ("_", dollar_vars[0]);
276 /* Remember this pid. */
277 dollar_dollar_pid = getpid ();
279 /* Now make our own defaults in case the vars that we think are
280 important are missing. */
281 temp_var = set_if_not ("PATH", DEFAULT_PATH_VALUE);
283 set_auto_export (temp_var); /* XXX */
286 temp_var = set_if_not ("TERM", "dumb");
288 set_auto_export (temp_var); /* XXX */
292 /* set node id -- don't import it from the environment */
295 qnx_nidtostr (getnid (), node_name, sizeof (node_name));
296 temp_var = bind_variable ("NODE", node_name);
297 set_auto_export (temp_var);
301 /* set up the prompts. */
302 if (interactive_shell)
304 #if defined (PROMPT_STRING_DECODE)
305 set_if_not ("PS1", primary_prompt);
307 if (current_user.uid == -1)
308 get_current_user_info ();
309 set_if_not ("PS1", current_user.euid == 0 ? "# " : primary_prompt);
311 set_if_not ("PS2", secondary_prompt);
313 set_if_not ("PS4", "+ ");
315 /* Don't allow IFS to be imported from the environment. */
316 temp_var = bind_variable ("IFS", " \t\n");
318 /* Magic machine types. Pretty convenient. */
321 /* Default MAILCHECK for interactive shells. Defer the creation of a
322 default MAILPATH until the startup files are read, because MAIL
323 names a mail file if MAILPATH is not set, and we should provide a
324 default only if neither is set. */
325 if (interactive_shell)
326 set_if_not ("MAILCHECK", posixly_correct ? "600" : "60");
328 /* Do some things with shell level. */
329 initialize_shell_level ();
333 /* Initialize the `getopts' stuff. */
334 bind_variable ("OPTIND", "1");
336 bind_variable ("OPTERR", "1");
339 if (login_shell == 1)
342 /* Get the full pathname to THIS shell, and set the BASH variable
344 name = get_bash_name ();
345 temp_var = bind_variable ("BASH", name);
348 /* Make the exported environment variable SHELL be the user's login
349 shell. Note that the `tset' command looks at this variable
350 to determine what style of commands to output; if it ends in "csh",
351 then C-shell commands are output, else Bourne shell commands. */
354 /* Make a variable called BASH_VERSION which contains the version info. */
355 bind_variable ("BASH_VERSION", shell_version_string ());
356 #if defined (ARRAY_VARS)
360 /* Find out if we're supposed to be in Posix.2 mode via an
361 environment variable. */
362 temp_var = find_variable ("POSIXLY_CORRECT");
364 temp_var = find_variable ("POSIX_PEDANTIC");
365 if (temp_var && imported_p (temp_var))
366 sv_strict_posix (temp_var->name);
368 #if defined (HISTORY)
369 /* Set history variables to defaults, and then do whatever we would
370 do if the variable had just been set. Do this only in the case
371 that we are remembering commands on the history list. */
372 if (remember_on_history)
374 name = bash_tilde_expand (posixly_correct ? "~/.sh_history" : "~/.bash_history");
376 set_if_not ("HISTFILE", name);
379 set_if_not ("HISTSIZE", "500");
380 sv_histsize ("HISTSIZE");
384 /* Seed the random number generator. */
385 sbrand (dollar_dollar_pid + shell_start_time);
387 /* Handle some "special" variables that we may have inherited from a
389 if (interactive_shell)
391 temp_var = find_variable ("IGNOREEOF");
393 temp_var = find_variable ("ignoreeof");
394 if (temp_var && imported_p (temp_var))
395 sv_ignoreeof (temp_var->name);
398 #if defined (HISTORY)
399 if (interactive_shell && remember_on_history)
401 sv_history_control ("HISTCONTROL");
402 sv_histignore ("HISTIGNORE");
409 * I'm tired of the arguing and bug reports. Bash now leaves SSH_CLIENT
410 * and SSH2_CLIENT alone. I'm going to rely on the shell_level check in
411 * isnetconn() to avoid running the startup files more often than wanted.
412 * That will, of course, only work if the user's login shell is bash, so
413 * I've made that behavior conditional on SSH_SOURCE_BASHRC being defined
417 temp_var = find_variable ("SSH_CLIENT");
418 if (temp_var && imported_p (temp_var))
420 VUNSETATTR (temp_var, att_exported);
421 array_needs_making = 1;
423 temp_var = find_variable ("SSH2_CLIENT");
424 if (temp_var && imported_p (temp_var))
426 VUNSETATTR (temp_var, att_exported);
427 array_needs_making = 1;
431 /* Get the user's real and effective user ids. */
434 /* Initialize the dynamic variables, and seed their values. */
435 initialize_dynamic_variables ();
443 temp_var = set_if_not ("HOSTTYPE", HOSTTYPE);
444 temp_var = set_if_not ("OSTYPE", OSTYPE);
445 temp_var = set_if_not ("MACHTYPE", MACHTYPE);
447 temp_var = set_if_not ("HOSTNAME", current_host_name);
450 /* Set $HOME to the information in the password file if we didn't get
451 it from the environment. */
453 /* This function is not static so the tilde and readline libraries can
458 if (current_user.home_dir == 0)
459 get_current_user_info ();
460 return current_user.home_dir;
468 temp_var = find_variable ("HOME");
470 temp_var = bind_variable ("HOME", sh_get_home_dir ());
472 VSETATTR (temp_var, att_exported);
476 /* Set $SHELL to the user's login shell if it is not already set. Call
477 get_current_user_info if we haven't already fetched the shell. */
483 temp_var = find_variable ("SHELL");
486 if (current_user.shell == 0)
487 get_current_user_info ();
488 temp_var = bind_variable ("SHELL", current_user.shell);
491 VSETATTR (temp_var, att_exported);
500 if ((login_shell == 1) && RELPATH(shell_name))
502 if (current_user.shell == 0)
503 get_current_user_info ();
504 name = savestring (current_user.shell);
506 else if (ABSPATH(shell_name))
507 name = savestring (shell_name);
508 else if (shell_name[0] == '.' && shell_name[1] == '/')
510 /* Fast path for common case. */
514 cdir = get_string_value ("PWD");
518 name = (char *)xmalloc (len + strlen (shell_name) + 1);
520 strcpy (name + len, shell_name + 1);
523 name = savestring (shell_name);
530 tname = find_user_command (shell_name);
534 /* Try the current directory. If there is not an executable
535 there, just punt and use the login shell. */
536 s = file_status (shell_name);
539 tname = make_absolute (shell_name, get_string_value ("PWD"));
540 if (*shell_name == '.')
542 name = sh_canonpath (tname, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
553 if (current_user.shell == 0)
554 get_current_user_info ();
555 name = savestring (current_user.shell);
560 name = full_pathname (tname);
569 adjust_shell_level (change)
572 char new_level[5], *old_SHLVL;
576 old_SHLVL = get_string_value ("SHLVL");
577 if (old_SHLVL == 0 || *old_SHLVL == '\0' || legal_number (old_SHLVL, &old_level) == 0)
580 shell_level = old_level + change;
583 else if (shell_level > 1000)
585 internal_warning ("shell level (%d) too high, resetting to 1", shell_level);
589 /* We don't need the full generality of itos here. */
590 if (shell_level < 10)
592 new_level[0] = shell_level + '0';
595 else if (shell_level < 100)
597 new_level[0] = (shell_level / 10) + '0';
598 new_level[1] = (shell_level % 10) + '0';
601 else if (shell_level < 1000)
603 new_level[0] = (shell_level / 100) + '0';
604 old_level = shell_level % 100;
605 new_level[1] = (old_level / 10) + '0';
606 new_level[2] = (old_level % 10) + '0';
610 temp_var = bind_variable ("SHLVL", new_level);
611 set_auto_export (temp_var);
615 initialize_shell_level ()
617 adjust_shell_level (1);
620 /* If we got PWD from the environment, update our idea of the current
621 working directory. In any case, make sure that PWD exists before
622 checking it. It is possible for getcwd () to fail on shell startup,
623 and in that case, PWD would be undefined. If this is an interactive
624 login shell, see if $HOME is the current working directory, and if
625 that's not the same string as $PWD, set PWD=$HOME. */
630 SHELL_VAR *temp_var, *home_var;
631 char *temp_string, *home_string;
633 home_var = find_variable ("HOME");
634 home_string = home_var ? value_cell (home_var) : (char *)NULL;
636 temp_var = find_variable ("PWD");
637 if (temp_var && imported_p (temp_var) &&
638 (temp_string = value_cell (temp_var)) &&
639 same_file (temp_string, ".", (struct stat *)NULL, (struct stat *)NULL))
640 set_working_directory (temp_string);
641 else if (home_string && interactive_shell && login_shell &&
642 same_file (home_string, ".", (struct stat *)NULL, (struct stat *)NULL))
644 set_working_directory (home_string);
645 temp_var = bind_variable ("PWD", home_string);
646 set_auto_export (temp_var);
650 temp_string = get_working_directory ("shell-init");
653 temp_var = bind_variable ("PWD", temp_string);
654 set_auto_export (temp_var);
659 /* According to the Single Unix Specification, v2, $OLDPWD is an
660 `environment variable' and therefore should be auto-exported.
661 Make a dummy invisible variable for OLDPWD, and mark it as exported. */
662 temp_var = bind_variable ("OLDPWD", (char *)NULL);
663 VSETATTR (temp_var, (att_exported | att_invisible));
666 /* Make a variable $PPID, which holds the pid of the shell's parent. */
670 char namebuf[INT_STRLEN_BOUND(pid_t) + 1], *name;
673 name = inttostr (getppid (), namebuf, sizeof(namebuf));
674 temp_var = find_variable ("PPID");
676 VUNSETATTR (temp_var, (att_readonly | att_exported));
677 temp_var = bind_variable ("PPID", name);
678 VSETATTR (temp_var, (att_readonly | att_integer));
684 char buff[INT_STRLEN_BOUND(uid_t) + 1], *b;
685 register SHELL_VAR *v;
687 b = inttostr (current_user.uid, buff, sizeof (buff));
688 v = find_variable ("UID");
691 v = bind_variable ("UID", b);
692 VSETATTR (v, (att_readonly | att_integer));
695 if (current_user.euid != current_user.uid)
696 b = inttostr (current_user.euid, buff, sizeof (buff));
698 v = find_variable ("EUID");
701 v = bind_variable ("EUID", b);
702 VSETATTR (v, (att_readonly | att_integer));
706 #if defined (ARRAY_VARS)
712 char *s, d[32], b[INT_STRLEN_BOUND(int) + 1];
714 makunbound ("BASH_VERSINFO", shell_variables);
716 vv = make_new_array_variable ("BASH_VERSINFO");
717 av = array_cell (vv);
718 strcpy (d, dist_version);
722 array_add_element (av, 0, d);
723 array_add_element (av, 1, s);
724 s = inttostr (patch_level, b, sizeof (b));
725 array_add_element (av, 2, s);
726 s = inttostr (build_version, b, sizeof (b));
727 array_add_element (av, 3, s);
728 array_add_element (av, 4, release_status);
729 array_add_element (av, 5, MACHTYPE);
731 VSETATTR (vv, att_readonly);
733 #endif /* ARRAY_VARS */
735 /* Set the environment variables $LINES and $COLUMNS in response to
736 a window size change. */
738 sh_set_lines_and_columns (lines, cols)
741 char val[INT_STRLEN_BOUND(int) + 1], *v;
743 v = inttostr (lines, val, sizeof (val));
744 bind_variable ("LINES", v);
746 v = inttostr (cols, val, sizeof (val));
747 bind_variable ("COLUMNS", v);
750 /* Set NAME to VALUE if NAME has no value. */
752 set_if_not (name, value)
757 v = find_variable (name);
759 v = bind_variable (name, value);
763 /* Map FUNCTION over the variables in VARIABLES. Return an array of the
764 variables for which FUNCTION returns a non-zero value. A NULL value
765 for FUNCTION means to use all variables. */
767 map_over (function, var_hash_table)
768 sh_var_map_func_t *function;
769 HASH_TABLE *var_hash_table;
772 register BUCKET_CONTENTS *tlist;
773 SHELL_VAR *var, **list;
774 int list_index, list_size;
776 list = (SHELL_VAR **)NULL;
777 for (i = list_index = list_size = 0; i < var_hash_table->nbuckets; i++)
779 tlist = get_hash_bucket (i, var_hash_table);
783 var = (SHELL_VAR *)tlist->data;
785 if (!function || (*function) (var))
787 if (list_index + 1 >= list_size)
788 list = (SHELL_VAR **)
789 xrealloc (list, (list_size += 20) * sizeof (SHELL_VAR *));
791 list[list_index++] = var;
792 list[list_index] = (SHELL_VAR *)NULL;
801 sort_variables (array)
804 qsort (array, array_len ((char **)array), sizeof (SHELL_VAR *), (QSFUNC *)qsort_var_comp);
808 qsort_var_comp (var1, var2)
809 SHELL_VAR **var1, **var2;
813 if ((result = (*var1)->name[0] - (*var2)->name[0]) == 0)
814 result = strcmp ((*var1)->name, (*var2)->name);
819 /* Create a NULL terminated array of all the shell variables in TABLE. */
826 list = map_over ((sh_var_map_func_t *)NULL, table);
827 if (list /* && posixly_correct */)
828 sort_variables (list);
832 /* Create a NULL terminated array of all the shell variables. */
834 all_shell_variables ()
836 return (all_vars (shell_variables));
839 /* Create a NULL terminated array of all the shell functions. */
841 all_shell_functions ()
843 return (all_vars (shell_functions));
846 /* Print LIST (a list of shell variables) to stdout in such a way that
847 they can be read back in. */
849 print_var_list (list)
850 register SHELL_VAR **list;
853 register SHELL_VAR *var;
855 for (i = 0; list && (var = list[i]); i++)
856 if (!invisible_p (var))
857 print_assignment (var);
860 /* Print LIST (a list of shell functions) to stdout in such a way that
861 they can be read back in. */
863 print_func_list (list)
864 register SHELL_VAR **list;
867 register SHELL_VAR *var;
869 for (i = 0; list && (var = list[i]); i++)
871 printf ("%s ", var->name);
872 print_var_function (var);
878 /* Print LIST (a linked list of shell variables) to stdout
879 by printing the names, without the values. Used to support the
882 print_vars_no_values (list)
883 register SHELL_VAR **list;
886 register SHELL_VAR *var;
888 for (i = 0; list && (var = list[i]); i++)
889 if (!invisible_p (var))
890 printf ("%s\n", var->name);
894 /* Print the value of a single SHELL_VAR. No newline is
895 output, but the variable is printed in such a way that
896 it can be read back in. */
898 print_assignment (var)
901 if (function_p (var) && var->value)
903 printf ("%s", var->name);
904 print_var_function (var);
907 #if defined (ARRAY_VARS)
908 else if (array_p (var) && var->value)
909 print_array_assignment (var, 0);
910 #endif /* ARRAY_VARS */
913 printf ("%s=", var->name);
914 print_var_value (var, 1);
919 /* Print the value cell of VAR, a shell variable. Do not print
920 the name, nor leading/trailing newline. If QUOTE is non-zero,
921 and the value contains shell metacharacters, quote the value
922 in such a way that it can be read back in. */
924 print_var_value (var, quote)
932 if (quote && posixly_correct == 0 && ansic_shouldquote (var->value))
934 t = ansic_quote (var->value, 0, (int *)0);
938 else if (quote && sh_contains_shell_metas (var->value))
940 t = sh_single_quote (var->value);
945 printf ("%s", var->value);
949 /* Print the function cell of VAR, a shell variable. Do not
950 print the name, nor leading/trailing newline. */
952 print_var_function (var)
955 if (function_p (var) && var->value)
956 printf ("%s", named_function_string ((char *)NULL, function_cell(var), 1));
959 /* **************************************************************** */
961 /* Dynamic Variable Extension */
963 /* **************************************************************** */
967 These are variables whose values are generated anew each time they are
968 referenced. These are implemented using a pair of function pointers
969 in the struct variable: assign_func, which is called from bind_variable,
970 and dynamic_value, which is called from find_variable.
972 assign_func is called from bind_variable, if bind_variable discovers
973 that the variable being assigned to has such a function. The function
975 SHELL_VAR *temp = (*(entry->assign_func)) (entry, value)
976 and the (SHELL_VAR *)temp is returned as the value of bind_variable. It
977 is usually ENTRY (self).
979 dynamic_value is called from find_variable to return a `new' value for
980 the specified dynamic varible. If this function is NULL, the variable
981 is treated as a `normal' shell variable. If it is not, however, then
982 this function is called like this:
983 tempvar = (*(var->dynamic_value)) (var);
985 Sometimes `tempvar' will replace the value of `var'. Other times, the
986 shell will simply use the string value. Pretty object-oriented, huh?
988 Be warned, though: if you `unset' a special variable, it loses its
989 special meaning, even if you subsequently set it.
991 The special assignment code would probably have been better put in
992 subst.c: do_assignment, in the same style as
993 stupidly_hack_special_variables, but I wanted the changes as
994 localized as possible. */
996 #define INIT_DYNAMIC_VAR(var, val, gfunc, afunc) \
999 v = bind_variable (var, (val)); \
1000 v->dynamic_value = gfunc; \
1001 v->assign_func = afunc; \
1005 #define INIT_DYNAMIC_ARRAY_VAR(var, gfunc, afunc) \
1008 v = make_new_array_variable (var); \
1009 v->dynamic_value = gfunc; \
1010 v->assign_func = afunc; \
1015 null_assign (self, value)
1022 #if defined (ARRAY_VARS)
1024 null_array_assign (self, ind, value)
1033 /* The value of $SECONDS. This is the number of seconds since shell
1034 invocation, or, the number of seconds since the last assignment + the
1035 value of the last assignment. */
1036 static long seconds_value_assigned;
1039 assign_seconds (self, value)
1043 if (legal_number (value, &seconds_value_assigned) == 0)
1044 seconds_value_assigned = 0;
1045 shell_start_time = NOW;
1053 time_t time_since_start;
1056 time_since_start = NOW - shell_start_time;
1057 p = itos(seconds_value_assigned + time_since_start);
1061 VSETATTR (var, att_integer);
1071 v = find_variable ("SECONDS");
1074 if (legal_number (value_cell(v), &seconds_value_assigned) == 0)
1075 seconds_value_assigned = 0;
1077 INIT_DYNAMIC_VAR ("SECONDS", (v ? v->value : (char *)NULL), get_seconds, assign_seconds);
1081 /* The random number seed. You can change this by setting RANDOM. */
1082 static unsigned long rseed = 1;
1083 static int last_random_value;
1085 /* A linear congruential random number generator based on the example
1086 on in the ANSI C standard. This one isn't very good, but a more
1087 complicated one is overkill. */
1089 /* Returns a pseudo-random number between 0 and 32767. */
1093 rseed = rseed * 1103515245 + 12345;
1094 return ((unsigned int)((rseed >> 16) & 32767)); /* was % 32768 */
1097 /* Set the random number generator seed to SEED. */
1103 last_random_value = 0;
1107 assign_random (self, value)
1111 sbrand (strtoul (value, (char **)NULL, 10));
1116 get_random_number ()
1120 /* Reset for command and process substitution. */
1121 if (subshell_environment)
1122 sbrand (rseed + getpid() + NOW);
1126 while (rv == last_random_value);
1137 rv = get_random_number ();
1138 last_random_value = rv;
1143 VSETATTR (var, att_integer);
1148 /* Function which returns the current line number. */
1156 ln = executing_line_number ();
1164 assign_lineno (var, value)
1170 if (value == 0 || *value == '\0' || legal_number (value, &new_value) == 0)
1172 line_number = new_value;
1176 #if defined (HISTORY)
1183 p = itos (history_number ());
1190 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1198 l = get_directory_stack ();
1199 a = word_list_to_array (l);
1200 dispose_array (array_cell (self));
1202 self->value = (char *)a;
1207 assign_dirstack (self, ind, value)
1212 set_dirstack_element (ind, 1, value);
1217 init_dirstack_var ()
1221 v = find_variable ("DIRSTACK");
1224 INIT_DYNAMIC_ARRAY_VAR ("DIRSTACK", get_dirstack, assign_dirstack);
1227 #endif /* PUSHD AND POPD && ARRAY_VARS */
1229 #if defined (ARRAY_VARS)
1230 /* We don't want to initialize the group set with a call to getgroups()
1231 unless we're asked to, but we only want to do it once. */
1239 static char **group_set = (char **)NULL;
1243 group_set = get_group_list (&ng);
1244 a = array_cell (self);
1245 for (i = 0; i < ng; i++)
1246 array_add_element (a, i, group_set[i]);
1256 v = find_variable ("GROUPS");
1259 INIT_DYNAMIC_ARRAY_VAR ("GROUPS", get_groupset, null_array_assign);
1260 VSETATTR (v, att_noassign);
1263 #endif /* ARRAY_VARS */
1269 if (variable_context && this_shell_function)
1272 self->value = savestring (this_shell_function->name);
1278 make_funcname_visible (on_or_off)
1283 v = find_variable ("FUNCNAME");
1284 if (v == 0 || v->dynamic_value == 0)
1288 VUNSETATTR (v, att_invisible);
1290 VSETATTR (v, att_invisible);
1294 init_funcname_var ()
1298 v = find_variable ("FUNCNAME");
1301 INIT_DYNAMIC_VAR ("FUNCNAME", (char *)NULL, get_funcname, null_assign);
1302 VSETATTR (v, att_invisible|att_noassign);
1307 initialize_dynamic_variables ()
1311 v = init_seconds_var ();
1313 INIT_DYNAMIC_VAR ("RANDOM", (char *)NULL, get_random, assign_random);
1314 INIT_DYNAMIC_VAR ("LINENO", (char *)NULL, get_lineno, assign_lineno);
1316 #if defined (HISTORY)
1317 INIT_DYNAMIC_VAR ("HISTCMD", (char *)NULL, get_histcmd, (DYNAMIC_FUNC *)NULL);
1320 #if defined (PUSHD_AND_POPD) && defined (ARRAY_VARS)
1321 v = init_dirstack_var ();
1322 #endif /* PUSHD_AND_POPD && ARRAY_VARS */
1324 #if defined (ARRAY_VARS)
1325 v = init_groups_var ();
1328 v = init_funcname_var ();
1331 /* How to get a pointer to the shell variable or function named NAME.
1332 HASHED_VARS is a pointer to the hash table containing the list
1333 of interest (either variables or functions). */
1335 var_lookup (name, hashed_vars)
1337 HASH_TABLE *hashed_vars;
1339 BUCKET_CONTENTS *bucket;
1341 bucket = find_hash_item (name, hashed_vars);
1342 return (bucket ? (SHELL_VAR *)bucket->data : (SHELL_VAR *)NULL);
1345 /* Look up the variable entry named NAME. If SEARCH_TEMPENV is non-zero,
1346 then also search the temporarily built list of exported variables. */
1348 find_variable_internal (name, search_tempenv)
1354 var = (SHELL_VAR *)NULL;
1356 /* If explicitly requested, first look in the temporary environment for
1357 the variable. This allows constructs such as "foo=x eval 'echo $foo'"
1358 to get the `exported' value of $foo. This happens if we are executing
1359 a function or builtin, or if we are looking up a variable in a
1360 "subshell environment". */
1361 if ((search_tempenv || subshell_environment) &&
1362 (temporary_env || builtin_env || function_env))
1363 var = find_tempenv_variable (name);
1366 var = var_lookup (name, shell_variables);
1369 return ((SHELL_VAR *)NULL);
1371 return (var->dynamic_value ? (*(var->dynamic_value)) (var) : var);
1374 /* Look up the variable entry named NAME. Returns the entry or NULL. */
1376 find_variable (name)
1379 return (find_variable_internal
1380 (name, (variable_context || this_shell_builtin || builtin_env)));
1383 /* Look up the function entry whose name matches STRING.
1384 Returns the entry or NULL. */
1386 find_function (name)
1389 return (var_lookup (name, shell_functions));
1392 /* Return the string value of a variable. Return NULL if the variable
1393 doesn't exist, or only has a function as a value. Don't cons a new
1394 string. This is a potential memory leak if the variable is found
1395 in the temporary environment. */
1397 get_string_value (var_name)
1398 const char *var_name;
1402 var = find_variable (var_name);
1405 return (char *)NULL;
1406 #if defined (ARRAY_VARS)
1407 else if (array_p (var))
1408 return (array_reference (array_cell (var), 0));
1411 return (var->value);
1414 /* This is present for use by the tilde and readline libraries. */
1416 sh_get_env_value (v)
1419 return get_string_value (v);
1422 /* Create a local variable referenced by NAME. */
1424 make_local_variable (name)
1427 SHELL_VAR *new_var, *old_var;
1428 BUCKET_CONTENTS *elt;
1430 /* local foo; local foo; is a no-op. */
1431 old_var = find_variable (name);
1432 if (old_var && old_var->context == variable_context)
1435 /* Since this is called only from the local/declare/typeset code, we can
1436 call builtin_error here without worry (of course, it will also work
1437 for anything that sets this_command_name). Variables with the `noassign'
1438 attribute may not be made local. The test against old_var's context
1439 level is to disallow local copies of readonly global variables (since I
1440 believe that this could be a security hole). Readonly copies of calling
1441 function local variables are OK. */
1442 if (old_var && (noassign_p (old_var) ||
1443 (readonly_p (old_var) && old_var->context == 0)))
1445 if (readonly_p (old_var))
1446 builtin_error ("%s: readonly variable", name);
1447 return ((SHELL_VAR *)NULL);
1450 elt = remove_hash_item (name, shell_variables);
1453 old_var = (SHELL_VAR *)elt->data;
1458 old_var = (SHELL_VAR *)NULL;
1460 /* If a variable does not already exist with this name, then
1461 just make a new one. */
1463 new_var = bind_variable (name, "");
1466 new_var = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1468 new_var->name = savestring (name);
1469 new_var->value = (char *)xmalloc (1);
1470 new_var->value[0] = '\0';
1472 CLEAR_EXPORTSTR (new_var);
1474 new_var->dynamic_value = (DYNAMIC_FUNC *)NULL;
1475 new_var->assign_func = (DYNAMIC_FUNC *)NULL;
1477 new_var->attributes = exported_p (old_var) ? att_exported : 0;
1479 new_var->prev_context = old_var;
1480 elt = add_hash_item (savestring (name), shell_variables);
1481 elt->data = (char *)new_var;
1484 new_var->context = variable_context;
1485 VSETATTR (new_var, att_local);
1488 if (variable_context >= local_variable_stack_size)
1490 int old_size = local_variable_stack_size;
1491 RESIZE_MALLOCED_BUFFER (have_local_variables, variable_context, 1,
1492 local_variable_stack_size, 8);
1493 bzero ((char *)have_local_variables + old_size,
1494 local_variable_stack_size - old_size);
1496 have_local_variables[variable_context] = 1; /* XXX */
1501 #if defined (ARRAY_VARS)
1503 make_local_array_variable (name)
1509 var = make_local_variable (name);
1512 array = new_array ();
1514 FREE (value_cell(var));
1515 var->value = (char *)array;
1516 VSETATTR (var, att_array);
1519 #endif /* ARRAY_VARS */
1521 /* Create a new shell variable with name NAME and add it to the hash table
1522 of shell variables. */
1524 make_new_variable (name)
1528 BUCKET_CONTENTS *elt;
1530 entry = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1532 entry->attributes = 0;
1533 entry->name = savestring (name);
1534 entry->value = (char *)NULL;
1535 CLEAR_EXPORTSTR (entry);
1537 entry->dynamic_value = (DYNAMIC_FUNC *)NULL;
1538 entry->assign_func = (DYNAMIC_FUNC *)NULL;
1540 /* Always assume variables are to be made at toplevel!
1541 make_local_variable has the responsibilty of changing the
1542 variable context. */
1544 entry->prev_context = (SHELL_VAR *)NULL;
1546 /* Make sure we have a shell_variables hash table to add to. */
1547 if (shell_variables == 0)
1548 shell_variables = make_hash_table (0);
1550 elt = add_hash_item (savestring (name), shell_variables);
1551 elt->data = (char *)entry;
1556 #if defined (ARRAY_VARS)
1558 make_new_array_variable (name)
1564 entry = make_new_variable (name);
1565 array = new_array ();
1566 entry->value = (char *)array;
1567 VSETATTR (entry, att_array);
1573 make_variable_value (var, value)
1581 /* If this variable has had its type set to integer (via `declare -i'),
1582 then do expression evaluation on it and store the result. The
1583 functions in expr.c (evalexp and bind_int_variable) are responsible
1584 for turning off the integer flag if they don't want further
1586 if (integer_p (var))
1588 lval = evalexp (value, &expok);
1590 jump_to_top_level (DISCARD);
1591 retval = itos (lval);
1596 retval = savestring (value);
1599 retval = (char *)xmalloc (1);
1604 retval = (char *)NULL;
1609 /* Bind a variable NAME to VALUE. This conses up the name
1610 and value strings. */
1612 bind_variable (name, value)
1617 SHELL_VAR *entry, *tempenv_entry;
1619 entry = (SHELL_VAR *)0;
1621 /* If we have a temporary environment, look there first for the variable,
1622 and, if found, modify the value there before modifying it in the
1623 shell_variables table. This allows sourced scripts to modify values
1624 given to them in a temporary environment while modifying the variable
1625 value that the caller sees. */
1626 if (temporary_env || builtin_env || function_env)
1628 tempenv_entry = find_tempenv_variable (name);
1631 dispose_variable (tempenv_entry);
1632 tempenv_entry = bind_tempenv_variable (name, value);
1633 dispose_variable (tempenv_entry);
1637 entry = var_lookup (name, shell_variables);
1641 entry = make_new_variable (name);
1642 entry->value = make_variable_value (entry, value);
1644 else if (entry->assign_func) /* array vars have assign functions now */
1646 INVALIDATE_EXPORTSTR (entry);
1647 return ((*(entry->assign_func)) (entry, value));
1651 if (readonly_p (entry) || noassign_p (entry))
1653 if (readonly_p (entry))
1654 report_error ("%s: readonly variable", name);
1658 /* Variables which are bound are visible. */
1659 VUNSETATTR (entry, att_invisible);
1661 newval = make_variable_value (entry, value);
1663 /* Invalidate any cached export string */
1664 INVALIDATE_EXPORTSTR (entry);
1666 #if defined (ARRAY_VARS)
1667 /* XXX -- this bears looking at again -- XXX */
1668 /* If an existing array variable x is being assigned to with x=b or
1669 `read x' or something of that nature, silently convert it to
1670 x[0]=b or `read x[0]'. */
1671 if (array_p (entry))
1673 array_add_element (array_cell (entry), 0, newval);
1679 FREE (entry->value);
1680 entry->value = newval;
1684 if (mark_modified_vars)
1685 VSETATTR (entry, att_exported);
1687 if (exported_p (entry))
1688 array_needs_making = 1;
1693 /* Make VAR, a simple shell variable, have value VALUE. Once assigned a
1694 value, variables are no longer invisible. This is a duplicate of part
1695 of the internals of bind_variable. If the variable is exported, or
1696 all modified variables should be exported, mark the variable for export
1697 and note that the export environment needs to be recreated. */
1699 bind_variable_value (var, value)
1705 VUNSETATTR (var, att_invisible);
1707 t = make_variable_value (var, value);
1711 INVALIDATE_EXPORTSTR (var);
1713 if (mark_modified_vars)
1714 VSETATTR (var, att_exported);
1716 if (exported_p (var))
1717 array_needs_making = 1;
1722 /* Bind/create a shell variable with the name LHS to the RHS.
1723 This creates or modifies a variable such that it is an integer.
1725 This used to be in expr.c, but it is here so that all of the
1726 variable binding stuff is localized. Since we don't want any
1727 recursive evaluation from bind_variable() (possible without this code,
1728 since bind_variable() calls the evaluator for variables with the integer
1729 attribute set), we temporarily turn off the integer attribute for each
1730 variable we set here, then turn it back on after binding as necessary. */
1733 bind_int_variable (lhs, rhs)
1736 register SHELL_VAR *v;
1740 v = find_variable (lhs);
1743 isint = integer_p (v);
1744 VUNSETATTR (v, att_integer);
1747 v = bind_variable (lhs, rhs);
1749 VSETATTR (v, att_integer);
1755 bind_var_to_int (var, val)
1759 char ibuf[INT_STRLEN_BOUND (long) + 1], *p;
1761 p = fmtulong (val, 10, ibuf, sizeof (ibuf), 0);
1762 return (bind_int_variable (var, p));
1765 /* Dispose of the information attached to VAR. */
1767 dispose_variable (var)
1773 if (function_p (var))
1774 dispose_command (function_cell (var));
1775 #if defined (ARRAY_VARS)
1776 else if (array_p (var))
1777 dispose_array (array_cell (var));
1780 FREE (value_cell (var));
1782 FREE_EXPORTSTR (var);
1786 if (exported_p (var))
1787 array_needs_making = 1;
1792 /* Unset the variable referenced by NAME. */
1794 unbind_variable (name)
1799 var = find_variable (name);
1803 /* This function should never be called with an array variable name. */
1804 #if defined (ARRAY_VARS)
1805 if (array_p (var) == 0 && var->value)
1811 var->value = (char *)NULL;
1814 makunbound (name, shell_variables);
1819 /* Make the variable associated with NAME go away. HASH_LIST is the
1820 hash table from which this variable should be deleted (either
1821 shell_variables or shell_functions).
1822 Returns non-zero if the variable couldn't be found. */
1824 makunbound (name, hash_list)
1826 HASH_TABLE *hash_list;
1828 BUCKET_CONTENTS *elt, *new_elt;
1829 SHELL_VAR *old_var, *new_var;
1832 elt = remove_hash_item (name, hash_list);
1837 old_var = (SHELL_VAR *)elt->data;
1838 new_var = old_var->prev_context;
1840 if (old_var && exported_p (old_var))
1841 array_needs_making++;
1843 #if defined (PROGRAMMABLE_COMPLETION)
1844 if (hash_list == shell_functions)
1845 set_itemlist_dirty (&it_functions);
1848 /* If we're unsetting a local variable and we're still executing inside
1849 the function, just mark the variable as invisible.
1850 kill_all_local_variables will clean it up later. This must be done
1851 so that if the variable is subsequently assigned a new value inside
1852 the function, the `local' attribute is still present. We also need
1853 to add it back into the correct hash table. */
1854 if (old_var && local_p (old_var) && variable_context == old_var->context)
1856 VSETATTR (old_var, att_invisible);
1857 INVALIDATE_EXPORTSTR (old_var);
1858 new_elt = add_hash_item (savestring (old_var->name), hash_list);
1859 new_elt->data = (char *)old_var;
1860 stupidly_hack_special_variables (old_var->name);
1868 /* Has to be a variable, functions don't have previous contexts. */
1869 new_elt = add_hash_item (savestring (new_var->name), hash_list);
1870 new_elt->data = (char *)new_var;
1872 if (exported_p (new_var))
1873 set_auto_export (new_var);
1876 /* Have to save a copy of name here, because it might refer to
1877 old_var->name. If so, stupidly_hack_special_variables will
1878 reference freed memory. */
1879 t = savestring (name);
1884 dispose_variable (old_var);
1885 stupidly_hack_special_variables (t);
1890 #ifdef INCLUDE_UNUSED
1891 /* Remove the variable with NAME if it is a local variable in the
1894 kill_local_variable (name)
1899 temp = find_variable (name);
1900 if (temp && temp->context == variable_context)
1902 makunbound (name, shell_variables);
1909 /* Get rid of all of the variables in the current context. */
1911 variable_in_context (var)
1914 return (var && var->context == variable_context);
1918 kill_all_local_variables ()
1920 register int i, pass;
1921 register SHELL_VAR *var, **list;
1922 HASH_TABLE *varlist;
1924 /* If HAVE_LOCAL_VARIABLES == 0, it means that we don't have any local
1925 variables at all. If VARIABLE_CONTEXT >= LOCAL_VARIABLE_STACK_SIZE,
1926 it means that we have some local variables, but not in this variable
1927 context (level of function nesting). Also, if
1928 HAVE_LOCAL_VARIABLES[VARIABLE_CONTEXT] == 0, we have no local variables
1930 if (have_local_variables == 0 ||
1931 variable_context >= local_variable_stack_size ||
1932 have_local_variables[variable_context] == 0)
1935 for (pass = 0; pass < 2; pass++)
1937 varlist = pass ? shell_functions : shell_variables;
1939 list = map_over (variable_in_context, varlist);
1943 for (i = 0; var = list[i]; i++)
1945 VUNSETATTR (var, att_local);
1946 makunbound (var->name, varlist);
1952 have_local_variables[variable_context] = 0; /* XXX */
1956 free_variable_hash_data (data)
1959 SHELL_VAR *var, *prev;
1961 var = (SHELL_VAR *)data;
1964 prev = var->prev_context;
1965 dispose_variable (var);
1970 /* Delete the entire contents of the hash table. */
1972 delete_all_variables (hashed_vars)
1973 HASH_TABLE *hashed_vars;
1975 flush_hash_table (hashed_vars, free_variable_hash_data);
1979 new_shell_variable (name)
1984 var = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
1986 bzero ((char *)var, sizeof (SHELL_VAR));
1987 var->name = savestring (name);
1991 /* Do a function binding to a variable. You pass the name and
1992 the command to bind to. This conses the name and command. */
1994 bind_function (name, value)
2000 entry = find_function (name);
2003 BUCKET_CONTENTS *elt;
2005 elt = add_hash_item (savestring (name), shell_functions);
2007 entry = new_shell_variable (name);
2008 entry->dynamic_value = entry->assign_func = (DYNAMIC_FUNC *)NULL;
2009 CLEAR_EXPORTSTR (entry);
2011 /* Functions are always made at the top level. This allows a
2012 function to define another function (like autoload). */
2015 elt->data = (char *)entry;
2018 INVALIDATE_EXPORTSTR (entry);
2021 dispose_command ((COMMAND *)entry->value);
2023 entry->value = value ? (char *)copy_command (value) : (char *)NULL;
2024 VSETATTR (entry, att_function);
2026 if (mark_modified_vars)
2027 VSETATTR (entry, att_exported);
2029 VUNSETATTR (entry, att_invisible); /* Just to be sure */
2031 if (exported_p (entry))
2032 array_needs_making = 1;
2034 #if defined (PROGRAMMABLE_COMPLETION)
2035 set_itemlist_dirty (&it_functions);
2041 #ifdef INCLUDE_UNUSED
2042 /* Copy VAR to a new data structure and return that structure. */
2047 SHELL_VAR *copy = (SHELL_VAR *)NULL;
2051 copy = (SHELL_VAR *)xmalloc (sizeof (SHELL_VAR));
2053 copy->attributes = var->attributes;
2054 copy->name = savestring (var->name);
2056 if (function_p (var))
2057 copy->value = (char *)copy_command (function_cell (var));
2058 #if defined (ARRAY_VARS)
2059 else if (array_p (var))
2060 copy->value = (char *)dup_array (array_cell (var));
2062 else if (value_cell (var))
2063 copy->value = savestring (value_cell (var));
2065 copy->value = (char *)NULL;
2067 copy->dynamic_value = var->dynamic_value;
2068 copy->assign_func = var->assign_func;
2070 copy->exportstr = COPY_EXPORTSTR (var);
2072 copy->context = var->context;
2074 /* Don't bother copying previous contexts along with this variable. */
2075 copy->prev_context = (SHELL_VAR *)NULL;
2081 #define FIND_OR_MAKE_VARIABLE(name, entry) \
2084 entry = find_variable (name); \
2087 entry = bind_variable (name, ""); \
2088 if (!no_invisible_vars) entry->attributes |= att_invisible; \
2093 /* Make the variable associated with NAME be readonly.
2094 If NAME does not exist yet, create it. */
2096 set_var_read_only (name)
2101 FIND_OR_MAKE_VARIABLE (name, entry);
2102 VSETATTR (entry, att_readonly);
2105 #ifdef INCLUDE_UNUSED
2106 /* Make the function associated with NAME be readonly.
2107 If NAME does not exist, we just punt, like auto_export code below. */
2109 set_func_read_only (name)
2114 entry = find_function (name);
2116 VSETATTR (entry, att_readonly);
2119 /* Make the variable associated with NAME be auto-exported.
2120 If NAME does not exist yet, create it. */
2122 set_var_auto_export (name)
2127 FIND_OR_MAKE_VARIABLE (name, entry);
2128 set_auto_export (entry);
2131 /* Make the function associated with NAME be auto-exported. */
2133 set_func_auto_export (name)
2138 entry = find_function (name);
2140 set_auto_export (entry);
2144 /* Returns non-zero if STRING is an assignment statement. The returned value
2145 is the index of the `=' sign. */
2150 register unsigned char c;
2151 register int newi, indx;
2153 c = string[indx = 0];
2155 if (legal_variable_starter (c) == 0)
2158 while (c = string[indx])
2160 /* The following is safe. Note that '=' at the start of a word
2161 is not an assignment statement. */
2165 #if defined (ARRAY_VARS)
2168 newi = skipsubscript (string, indx);
2169 if (string[newi++] != ']')
2171 return ((string[newi] == '=') ? newi : 0);
2173 #endif /* ARRAY_VARS */
2175 /* Variable names in assignment statements may contain only letters,
2177 if (legal_variable_char (c) == 0)
2189 return (invisible_p (var) == 0);
2193 _visible_names (table)
2198 list = map_over (visible_var, table);
2200 if (list /* && posixly_correct */)
2201 sort_variables (list);
2207 all_visible_functions ()
2209 return (_visible_names (shell_functions));
2213 all_visible_variables ()
2215 return (_visible_names (shell_variables));
2218 /* Return non-zero if the variable VAR is visible and exported. Array
2219 variables cannot be exported. */
2221 visible_and_exported (var)
2224 return (invisible_p (var) == 0 && exported_p (var));
2228 all_exported_variables ()
2232 list = map_over (visible_and_exported, shell_variables);
2234 sort_variables (list);
2238 #if defined (ARRAY_VARS)
2239 /* Return non-zero if the variable VAR is visible and an array. */
2241 visible_array_vars (var)
2244 return (invisible_p (var) == 0 && array_p (var));
2248 all_array_variables ()
2252 list = map_over (visible_array_vars, shell_variables);
2254 sort_variables (list);
2257 #endif /* ARRAY_VARS */
2260 all_variables_matching_prefix (prefix)
2263 SHELL_VAR **varlist;
2265 int vind, rind, plen;
2267 plen = STRLEN (prefix);
2268 varlist = all_visible_variables ();
2269 for (vind = 0; varlist && varlist[vind]; vind++)
2271 if (varlist == 0 || vind == 0)
2272 return ((char **)NULL);
2273 rlist = alloc_array (vind + 1);
2274 for (vind = rind = 0; varlist[vind]; vind++)
2276 if (plen == 0 || STREQN (prefix, varlist[vind]->name, plen))
2277 rlist[rind++] = savestring (varlist[vind]->name);
2279 rlist[rind] = (char *)0;
2285 static inline char *
2286 mk_env_string (name, value)
2287 const char *name, *value;
2289 int name_len, value_len;
2292 name_len = strlen (name);
2293 value_len = STRLEN (value);
2294 p = (char *)xmalloc (2 + name_len + value_len);
2297 if (value && *value)
2298 strcpy (p + name_len + 1, value);
2300 p[name_len + 1] = '\0';
2313 if (legal_variable_starter ((unsigned char)*s) == 0)
2315 internal_error ("invalid character %d in exportstr for %s", *s, v->name);
2318 for (s = v->exportstr + 1; s && *s; s++)
2322 if (legal_variable_char ((unsigned char)*s) == 0)
2324 internal_error ("invalid character %d in exportstr for %s", *s, v->name);
2330 internal_error ("no `=' in exportstr for %s", v->name);
2337 /* Make an array of assignment statements from the hash table
2338 HASHED_VARS which contains SHELL_VARs. Only visible, exported
2339 variables are eligible. */
2341 make_var_array (hashed_vars)
2342 HASH_TABLE *hashed_vars;
2344 register int i, list_index;
2345 register SHELL_VAR *var;
2346 char **list, *value;
2349 vars = map_over (visible_and_exported, hashed_vars);
2352 return (char **)NULL;
2354 list = alloc_array ((1 + array_len ((char **)vars)));
2356 #define USE_EXPORTSTR (value == var->exportstr)
2358 for (i = 0, list_index = 0; var = vars[i]; i++)
2360 #if defined (__CYGWIN__)
2361 /* We don't use the exportstr stuff on Cygwin at all. */
2362 INVALIDATE_EXPORTSTR (var);
2365 value = var->exportstr;
2366 else if (function_p (var))
2367 value = named_function_string ((char *)NULL, function_cell (var), 0);
2368 #if defined (ARRAY_VARS)
2369 else if (array_p (var))
2371 value = array_to_assignment_string (array_cell (var));
2373 continue; /* XXX array vars cannot yet be exported */
2377 value = value_cell (var);
2381 /* Gee, I'd like to get away with not using savestring() if we're
2382 using the cached exportstr... */
2383 list[list_index] = USE_EXPORTSTR ? savestring (value)
2384 : mk_env_string (var->name, value);
2386 if (USE_EXPORTSTR == 0 && function_p (var))
2388 SAVE_EXPORTSTR (var, list[list_index]);
2391 #undef USE_EXPORTSTR
2394 #if defined (ARRAY_VARS)
2403 list[list_index] = (char *)NULL;
2407 /* Add STRING to the array of foo=bar strings that we already
2408 have to add to the environment. */
2410 assign_in_env (string)
2414 char *name, *temp, *value;
2417 offset = assignment (string);
2418 name = savestring (string);
2419 value = (char *)NULL;
2421 if (name[offset] == '=')
2425 var = find_variable (name);
2426 if (var && (readonly_p (var) || noassign_p (var)))
2428 if (readonly_p (var))
2429 report_error ("%s: readonly variable", name);
2434 temp = name + offset + 1;
2435 temp = (strchr (temp, '~') != 0) ? bash_tilde_expand (temp) : savestring (temp);
2437 value = expand_string_unsplit_to_string (temp, 0);
2441 temp = mk_env_string (name, value);
2445 if (temporary_env == 0)
2447 temporary_env = (char **)xmalloc (sizeof (char *));
2448 temporary_env [0] = (char *)NULL;
2451 size = array_len (temporary_env);
2452 temporary_env = (char **)
2453 xrealloc (temporary_env, (size + 2) * (sizeof (char *)));
2455 temporary_env[size] = temp;
2456 temporary_env[size + 1] = (char *)NULL;
2457 array_needs_making = 1;
2459 if (echo_command_at_execute)
2461 /* The Korn shell prints the `+ ' in front of assignment statements,
2463 fprintf (stderr, "%s%s\n", indirection_level_string (), temp);
2470 /* Create a SHELL_VAR from a `name=value' string as in the environment, taking
2471 the variable name, the environment string, and an index into the string
2472 which is the offset of the `=' (the char before the value begins). */
2474 shell_var_from_env_string (name, env_string, l)
2482 /* This is a potential memory leak. The code should really save
2483 the created variables in some auxiliary data structure, which
2484 can be disposed of at the appropriate time. */
2485 temp = new_shell_variable (name);
2486 w = env_string + l + 1;
2488 temp->value = *w ? savestring (w) : (char *)NULL;
2490 temp->attributes = att_exported|att_tempvar;
2492 temp->prev_context = (SHELL_VAR *)NULL;
2494 temp->dynamic_value = temp->assign_func = (DYNAMIC_FUNC *)NULL;
2495 CLEAR_EXPORTSTR (temp);
2500 /* Bind NAME to VALUE in ARRAY, an array of strings in the same format as the
2501 environment array (i.e, name=value). If NAME is present, change the value,
2502 cons up a new SHELL_VAR and return it. Otherwise return (SHELL_VAR *)NULL. */
2505 bind_name_in_env_array (name, value, array)
2511 char *new_env_string;
2515 return ((SHELL_VAR *)NULL);
2517 for (i = 0, l = strlen (name); array[i]; i++)
2519 if (STREQN (array[i], name, l) && array[i][l] == '=')
2521 new_env_string = mk_env_string (name, value);
2523 temp = shell_var_from_env_string (name, new_env_string, l);
2526 array[i] = new_env_string;
2531 return ((SHELL_VAR *)NULL);
2534 /* Search for NAME in ARRAY, an array of strings in the same format as the
2535 environment array (i.e, name=value). If NAME is present, make a new
2536 variable and return it. Otherwise, return NULL. */
2538 find_name_in_env_array (name, array)
2546 return ((SHELL_VAR *)NULL);
2548 for (i = 0, l = strlen (name); array[i]; i++)
2550 if (STREQN (array[i], name, l) && array[i][l] == '=')
2552 temp = shell_var_from_env_string (name, array[i], l);
2556 return ((SHELL_VAR *)NULL);
2559 #define FIND_AND_BIND_IN_ENV_ARRAY(N, V, A) \
2562 var = find_name_in_env_array (N, A); \
2565 dispose_variable (var); \
2566 var = bind_name_in_env_array (N, V, A); \
2572 /* Make variable NAME have VALUE in one of the temporary environments. */
2574 bind_tempenv_variable (name, value)
2580 var = (SHELL_VAR *)NULL;
2583 FIND_AND_BIND_IN_ENV_ARRAY (name, value, temporary_env);
2585 /* We don't check this_shell_builtin because the command that needs the
2586 value from builtin_env may be a disk command run inside a script run
2587 with `.' and a temporary env. */
2589 FIND_AND_BIND_IN_ENV_ARRAY (name, value, builtin_env);
2591 if (variable_context && function_env)
2592 FIND_AND_BIND_IN_ENV_ARRAY (name, value, function_env);
2594 return (SHELL_VAR *)NULL;
2597 /* Find a variable in the temporary environment that is named NAME.
2598 The temporary environment can be either the environment provided
2599 to a simple command, or the environment provided to a shell function.
2600 We only search the function environment if we are currently executing
2601 a shell function body (variable_context > 0). Return a consed variable,
2602 or NULL if not found. */
2604 find_tempenv_variable (name)
2609 var = (SHELL_VAR *)NULL;
2612 var = find_name_in_env_array (name, temporary_env);
2614 /* We don't check this_shell_builtin because the command that needs the
2615 value from builtin_env may be a disk command run inside a script run
2616 with `.' and a temporary env. */
2617 if (!var && builtin_env)
2618 var = find_name_in_env_array (name, builtin_env);
2620 if (!var && variable_context && function_env)
2621 var = find_name_in_env_array (name, function_env);
2626 /* Free the storage allocated to the string array pointed to by ARRAYP, and
2627 make that variable have a null pointer as a value. */
2629 dispose_temporary_vars (arrayp)
2635 free_array (*arrayp);
2636 *arrayp = (char **)NULL;
2637 array_needs_making = 1;
2640 /* Free the storage used in the variable array for temporary
2641 environment variables. */
2643 dispose_used_env_vars ()
2645 dispose_temporary_vars (&temporary_env);
2648 /* Free the storage used for temporary environment variables given to
2649 commands when executing inside of a function body. */
2651 dispose_function_env ()
2653 dispose_temporary_vars (&function_env);
2656 /* Free the storage used for temporary environment variables given to
2657 commands when executing a builtin command such as "source". */
2659 dispose_builtin_env ()
2661 dispose_temporary_vars (&builtin_env);
2664 /* Take all of the shell variables in ENV_ARRAY and make shell variables
2665 from them at the current variable context. */
2667 merge_env_array (env_array)
2677 for (i = 0; env_array[i]; i++)
2679 l = assignment (env_array[i]);
2680 name = env_array[i];
2681 val = env_array[i] + l + 1;
2683 temp = bind_variable (name, val);
2689 merge_temporary_env ()
2691 merge_env_array (temporary_env);
2695 merge_builtin_env ()
2697 merge_env_array (builtin_env);
2701 merge_function_env ()
2703 merge_env_array (function_env);
2706 #ifdef INCLUDE_UNUSED
2708 any_temporary_variables ()
2710 return (temporary_env || function_env);
2714 /* Add ENVSTR to the end of the exported environment, EXPORT_ENV. */
2715 #define add_to_export_env(envstr,do_alloc) \
2718 if (export_env_index >= (export_env_size - 1)) \
2720 export_env_size += 16; \
2721 export_env = (char **)xrealloc (export_env, export_env_size * sizeof (char *)); \
2723 export_env[export_env_index++] = (do_alloc) ? savestring (envstr) : envstr; \
2724 export_env[export_env_index] = (char *)NULL; \
2727 #define ISFUNCTION(s, o) ((s[o + 1] == '(') && (s[o + 2] == ')'))
2729 /* Add ASSIGN to EXPORT_ENV, or supercede a previous assignment in the
2730 array with the same left-hand side. Return the new EXPORT_ENV. */
2732 add_or_supercede_exported_var (assign, do_alloc)
2739 equal_offset = assignment (assign);
2740 if (equal_offset == 0)
2741 return (export_env);
2743 /* If this is a function, then only supercede the function definition.
2744 We do this by including the `=(' in the comparison. */
2745 if (assign[equal_offset + 1] == '(')
2748 for (i = 0; i < export_env_index; i++)
2750 if (STREQN (assign, export_env[i], equal_offset + 1))
2752 free (export_env[i]);
2753 export_env[i] = do_alloc ? savestring (assign) : assign;
2754 return (export_env);
2757 add_to_export_env (assign, do_alloc);
2758 return (export_env);
2761 /* Make the environment array for the command about to be executed, if the
2762 array needs making. Otherwise, do nothing. If a shell action could
2763 change the array that commands receive for their environment, then the
2764 code should `array_needs_making++'. */
2766 maybe_make_export_env ()
2769 register char **temp_array;
2772 if (array_needs_making)
2775 free_array_members (export_env);
2777 /* Make a guess based on how many shell variables and functions we
2778 have. Since there will always be array variables, and array
2779 variables are not (yet) exported, this will always be big enough
2780 for the exported variables and functions, without any temporary
2781 or function environments. */
2782 new_size = HASH_ENTRIES (shell_variables) + HASH_ENTRIES (shell_functions) + 1;
2783 if (new_size > export_env_size)
2785 export_env_size = new_size;
2786 export_env = (char **)xrealloc (export_env, export_env_size * sizeof (char *));
2788 export_env[export_env_index = 0] = (char *)NULL;
2790 temp_array = make_var_array (shell_variables);
2793 for (i = 0; temp_array[i]; i++)
2794 add_to_export_env (temp_array[i], 0);
2798 #if defined (RESTRICTED_SHELL)
2799 /* Restricted shells may not export shell functions. */
2800 temp_array = restricted ? (char **)0 : make_var_array (shell_functions);
2802 temp_array = make_var_array (shell_functions);
2806 for (i = 0; temp_array[i]; i++)
2807 add_to_export_env (temp_array[i], 0);
2812 for (i = 0; function_env[i]; i++)
2813 export_env = add_or_supercede_exported_var (function_env[i], 1);
2816 for (i = 0; builtin_env[i]; i++)
2817 export_env = add_or_supercede_exported_var (builtin_env[i], 1);
2820 for (i = 0; temporary_env[i]; i++)
2821 export_env = add_or_supercede_exported_var (temporary_env[i], 1);
2824 /* If we changed the array, then sort it alphabetically. */
2825 if (posixly_correct == 0 && (temporary_env || function_env))
2826 sort_char_array (export_env);
2829 array_needs_making = 0;
2833 /* This is an efficiency hack. PWD and OLDPWD are auto-exported, so
2834 we will need to remake the exported environment every time we
2835 change directories. `_' is always put into the environment for
2836 every external command, so without special treatment it will always
2837 cause the environment to be remade.
2839 If there is no other reason to make the exported environment, we can
2840 just update the variables in place and mark the exported environment
2841 as no longer needing a remake. */
2843 update_export_env_inplace (env_prefix, preflen, value)
2850 evar = (char *)xmalloc (STRLEN (value) + preflen + 1);
2851 strcpy (evar, env_prefix);
2853 strcpy (evar + preflen, value);
2854 export_env = add_or_supercede_exported_var (evar, 0);
2857 /* We always put _ in the environment as the name of this command. */
2859 put_command_name_into_env (command_name)
2862 update_export_env_inplace ("_=", 2, command_name);
2865 #if 0 /* UNUSED -- it caused too many problems */
2867 put_gnu_argv_flags_into_env (pid, flags_string)
2877 fl = strlen (flags_string);
2879 dummy = (char *)xmalloc (l + fl + 30);
2881 strcpy (dummy + 1, pbuf);
2882 strcpy (dummy + 1 + l, "_GNU_nonoption_argv_flags_");
2883 dummy[l + 27] = '=';
2884 strcpy (dummy + l + 28, flags_string);
2888 export_env = add_or_supercede_exported_var (dummy, 0);
2892 /* Return a string denoting what our indirection level is. */
2893 static char indirection_string[100];
2896 indirection_level_string ()
2901 indirection_string[0] = '\0';
2902 ps4 = get_string_value ("PS4");
2904 if (ps4 == 0 || *ps4 == '\0')
2905 return (indirection_string);
2907 ps4 = decode_prompt_string (ps4);
2909 for (i = 0; *ps4 && i < indirection_level && i < 99; i++)
2910 indirection_string[i] = *ps4;
2912 for (j = 1; *ps4 && ps4[j] && i < 99; i++, j++)
2913 indirection_string[i] = ps4[j];
2915 indirection_string[i] = '\0';
2917 return (indirection_string);
2920 /*************************************************
2922 * Functions to manage special variables *
2924 *************************************************/
2926 /* Extern declarations for variables this code has to manage. */
2927 extern int eof_encountered, eof_encountered_limit, ignoreeof;
2929 #if defined (READLINE)
2930 extern int no_line_editing;
2931 extern int hostname_list_initialized;
2934 /* An alist of name.function for each special variable. Most of the
2935 functions don't do much, and in fact, this would be faster with a
2936 switch statement, but by the end of this file, I am sick of switch
2939 #define SET_INT_VAR(name, intvar) intvar = find_variable (name) != 0
2941 struct name_and_function {
2943 sh_sv_func_t *function;
2944 } special_vars[] = {
2945 { "PATH", sv_path },
2946 { "MAIL", sv_mail },
2947 { "MAILPATH", sv_mail },
2948 { "MAILCHECK", sv_mail },
2950 { "POSIXLY_CORRECT", sv_strict_posix },
2951 { "GLOBIGNORE", sv_globignore },
2953 /* Variables which only do something special when READLINE is defined. */
2954 #if defined (READLINE)
2955 { "TERM", sv_terminal },
2956 { "TERMCAP", sv_terminal },
2957 { "TERMINFO", sv_terminal },
2958 { "HOSTFILE", sv_hostfile },
2959 #endif /* READLINE */
2961 /* Variables which only do something special when HISTORY is defined. */
2962 #if defined (HISTORY)
2963 { "HISTIGNORE", sv_histignore },
2964 { "HISTSIZE", sv_histsize },
2965 { "HISTFILESIZE", sv_histsize },
2966 { "HISTCONTROL", sv_history_control },
2967 # if defined (BANG_HISTORY)
2968 { "histchars", sv_histchars },
2969 # endif /* BANG_HISTORY */
2970 #endif /* HISTORY */
2972 { "IGNOREEOF", sv_ignoreeof },
2973 { "ignoreeof", sv_ignoreeof },
2975 { "OPTIND", sv_optind },
2976 { "OPTERR", sv_opterr },
2978 { "TEXTDOMAIN", sv_locale },
2979 { "TEXTDOMAINDIR", sv_locale },
2980 { "LC_ALL", sv_locale },
2981 { "LC_COLLATE", sv_locale },
2982 { "LC_CTYPE", sv_locale },
2983 { "LC_MESSAGES", sv_locale },
2984 { "LC_NUMERIC", sv_locale },
2985 { "LANG", sv_locale },
2987 #if defined (HAVE_TZSET) && defined (PROMPT_STRING_DECODE)
2991 { (char *)0, (sh_sv_func_t *)0 }
2994 /* The variable in NAME has just had its state changed. Check to see if it
2995 is one of the special ones where something special happens. */
2997 stupidly_hack_special_variables (name)
3002 for (i = 0; special_vars[i].name; i++)
3004 if (STREQ (special_vars[i].name, name))
3006 (*(special_vars[i].function)) (name);
3012 /* What to do just after the PATH variable has changed. */
3018 flush_hashed_filenames ();
3021 /* What to do just after one of the MAILxxxx variables has changed. NAME
3022 is the name of the variable. This is called with NAME set to one of
3023 MAIL, MAILCHECK, or MAILPATH. */
3028 /* If the time interval for checking the files has changed, then
3029 reset the mail timer. Otherwise, one of the pathname vars
3030 to the users mailbox has changed, so rebuild the array of
3032 if (name[4] == 'C') /* if (strcmp (name, "MAILCHECK") == 0) */
3033 reset_mail_timer ();
3037 remember_mail_dates ();
3041 /* What to do when GLOBIGNORE changes. */
3043 sv_globignore (name)
3046 setup_glob_ignore (name);
3049 #if defined (READLINE)
3050 /* What to do just after one of the TERMxxx variables has changed.
3051 If we are an interactive shell, then try to reset the terminal
3052 information in readline. */
3057 if (interactive_shell && no_line_editing == 0)
3058 rl_reset_terminal (get_string_value ("TERM"));
3067 v = find_variable (name);
3069 clear_hostname_list ();
3071 hostname_list_initialized = 0;
3073 #endif /* READLINE */
3075 #if defined (HISTORY)
3076 /* What to do after the HISTSIZE or HISTFILESIZE variables change.
3077 If there is a value for this HISTSIZE (and it is numeric), then stifle
3078 the history. Otherwise, if there is NO value for this variable,
3079 unstifle the history. If name is HISTFILESIZE, and its value is
3080 numeric, truncate the history file to hold no more than that many
3089 temp = get_string_value (name);
3093 if (legal_number (temp, &num))
3097 stifle_history (num);
3098 num = where_history ();
3099 if (history_lines_this_session > num)
3100 history_lines_this_session = num;
3104 history_truncate_file (get_string_value ("HISTFILE"), (int)num);
3105 if (num <= history_lines_in_file)
3106 history_lines_in_file = num;
3110 else if (name[4] == 'S')
3111 unstifle_history ();
3114 /* What to do after the HISTIGNORE variable changes. */
3116 sv_histignore (name)
3119 setup_history_ignore (name);
3122 /* What to do after the HISTCONTROL variable changes. */
3124 sv_history_control (name)
3129 history_control = 0;
3130 temp = get_string_value (name);
3132 if (temp && *temp && STREQN (temp, "ignore", 6))
3134 if (temp[6] == 's') /* ignorespace */
3135 history_control = 1;
3136 else if (temp[6] == 'd') /* ignoredups */
3137 history_control = 2;
3138 else if (temp[6] == 'b') /* ignoreboth */
3139 history_control = 3;
3143 #if defined (BANG_HISTORY)
3144 /* Setting/unsetting of the history expansion character. */
3151 temp = get_string_value (name);
3154 history_expansion_char = *temp;
3155 if (temp[0] && temp[1])
3157 history_subst_char = temp[1];
3159 history_comment_char = temp[2];
3164 history_expansion_char = '!';
3165 history_subst_char = '^';
3166 history_comment_char = '#';
3169 #endif /* BANG_HISTORY */
3170 #endif /* HISTORY */
3172 #if defined (HAVE_TZSET) && defined (PROMPT_STRING_DECODE)
3181 /* If the variable exists, then the value of it can be the number
3182 of times we actually ignore the EOF. The default is small,
3183 (smaller than csh, anyway). */
3191 eof_encountered = 0;
3193 tmp_var = find_variable (name);
3194 ignoreeof = tmp_var != 0;
3195 temp = tmp_var ? value_cell (tmp_var) : (char *)NULL;
3197 eof_encountered_limit = (*temp && all_digits (temp)) ? atoi (temp) : 10;
3198 set_shellopts (); /* make sure `ignoreeof' is/is not in $SHELLOPTS */
3208 tt = get_string_value ("OPTIND");
3213 /* According to POSIX, setting OPTIND=1 resets the internal state
3215 if (s < 0 || s == 1)
3229 tt = get_string_value ("OPTERR");
3230 sh_opterr = (tt && *tt) ? atoi (tt) : 1;
3234 sv_strict_posix (name)
3237 SET_INT_VAR (name, posixly_correct);
3238 posix_initialize (posixly_correct);
3239 #if defined (READLINE)
3240 if (interactive_shell)
3241 posix_readline_initialize (posixly_correct);
3242 #endif /* READLINE */
3243 set_shellopts (); /* make sure `posix' is/is not in $SHELLOPTS */
3252 v = get_string_value (name);
3253 if (name[0] == 'L' && name[1] == 'A') /* LANG */
3256 set_locale_var (name, v); /* LC_*, TEXTDOMAIN* */
3259 #if defined (ARRAY_VARS)
3261 set_pipestatus_array (ps)
3267 char *t, tbuf[INT_STRLEN_BOUND(int) + 1];
3269 v = find_variable ("PIPESTATUS");
3271 v = make_new_array_variable ("PIPESTATUS");
3272 if (array_p (v) == 0)
3273 return; /* Do nothing if not an array variable. */
3277 for (i = 0; ps[i] != -1; i++)
3279 t = inttostr (ps[i], tbuf, sizeof (tbuf));
3280 array_add_element (a, i, t);
3286 set_pipestatus_from_exit (s)
3289 #if defined (ARRAY_VARS)
3290 static int v[2] = { 0, -1 };
3293 set_pipestatus_array (v);