1 /* shell.c -- GNU's idea of the POSIX shell specification. */
3 /* Copyright (C) 1987,1991 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.
22 Sunday, January 10th, 1988.
23 Initial author: Brian Fox
25 #define INSTALL_DEBUG_MODE
29 #include "bashtypes.h"
31 # include <sys/file.h>
33 #include "posixstat.h"
34 #include "posixtime.h"
42 #if defined (HAVE_UNISTD_H)
46 #define NEED_SH_SETLINEBUF_DECL /* used in externs.h */
51 #include "mailcheck.h"
53 #include "builtins/common.h"
55 #if defined (JOB_CONTROL)
57 #endif /* JOB_CONTROL */
60 #include "execute_cmd.h"
64 # include "bashhist.h"
65 # include <readline/history.h>
68 #include <tilde/tilde.h>
69 #include <glob/strmatch.h>
71 #if defined (__OPENNT)
72 # include <opennt/opennt.h>
75 #if !defined (HAVE_GETPW_DECLS)
76 extern struct passwd *getpwuid ();
77 #endif /* !HAVE_GETPW_DECLS */
83 #if defined (NO_MAIN_ENV_ARG)
84 extern char **environ; /* used if no third argument to main() */
87 extern char *dist_version, *release_status;
88 extern int patch_level, build_version;
89 extern int shell_level;
90 extern int subshell_environment;
91 extern int last_command_exit_value;
92 extern int line_number;
93 extern char *primary_prompt, *secondary_prompt;
94 extern int expand_aliases;
95 extern char *this_command_name;
96 extern int array_needs_making;
98 /* Non-zero means that this shell has already been run; i.e. you should
99 call shell_reinitialize () if you need to start afresh. */
100 int shell_initialized = 0;
102 COMMAND *global_command = (COMMAND *)NULL;
104 /* Information about the current user. */
105 struct user_info current_user =
107 (uid_t)-1, (uid_t)-1, (gid_t)-1, (gid_t)-1,
108 (char *)NULL, (char *)NULL, (char *)NULL
111 /* The current host's name. */
112 char *current_host_name = (char *)NULL;
114 /* Non-zero means that this shell is a login shell.
117 1 = login shell from getty (or equivalent fake out)
118 -1 = login shell from "--login" flag.
119 -2 = both from getty, and from flag.
123 /* Non-zero means that at this moment, the shell is interactive. In
124 general, this means that the shell is at this moment reading input
125 from the keyboard. */
128 /* Non-zero means that the shell was started as an interactive shell. */
129 int interactive_shell = 0;
131 /* Non-zero means to send a SIGHUP to all jobs when an interactive login
135 /* Tells what state the shell was in when it started:
136 0 = non-interactive shell script
139 This is a superset of the information provided by interactive_shell.
141 int startup_state = 0;
143 /* Special debugging helper. */
144 int debugging_login_shell = 0;
146 /* The environment that the shell passes to other commands. */
147 char **shell_environment;
149 /* Non-zero when we are executing a top-level command. */
152 /* The number of commands executed so far. */
153 int current_command_number = 1;
155 /* Non-zero is the recursion depth for commands. */
156 int indirection_level = 0;
158 /* The name of this shell, as taken from argv[0]. */
159 char *shell_name = (char *)NULL;
161 /* time in seconds when the shell was started */
162 time_t shell_start_time;
164 /* Are we running in an emacs shell window? */
165 int running_under_emacs;
167 /* The name of the .(shell)rc file. */
168 static char *bashrc_file = "~/.bashrc";
170 /* Non-zero means to act more like the Bourne shell on startup. */
171 static int act_like_sh;
173 /* Non-zero if this shell is being run by `su'. */
176 /* Non-zero if we have already expanded and sourced $ENV. */
177 static int sourced_env;
179 /* Is this shell running setuid? */
180 static int running_setuid;
182 /* Values for the long-winded argument names. */
183 static int debugging; /* Do debugging things. */
184 static int no_rc; /* Don't execute ~/.bashrc */
185 static int no_profile; /* Don't execute .profile */
186 static int do_version; /* Display interesting version info. */
187 static int make_login_shell; /* Make this shell be a `-bash' shell. */
188 static int want_initial_help; /* --help option */
190 int no_line_editing = 0; /* Don't do fancy line editing. */
191 int posixly_correct = 0; /* Non-zero means posix.2 superset. */
192 int dump_translatable_strings; /* Dump strings in $"...", don't execute. */
193 int dump_po_strings; /* Dump strings in $"..." in po format */
194 int wordexp_only = 0; /* Do word expansion only */
196 /* Some long-winded argument names. These are obviously new. */
205 { "debug", Int, &debugging, (char **)0x0 },
206 { "dump-po-strings", Int, &dump_po_strings, (char **)0x0 },
207 { "dump-strings", Int, &dump_translatable_strings, (char **)0x0 },
208 { "help", Int, &want_initial_help, (char **)0x0 },
209 { "init-file", Charp, (int *)0x0, &bashrc_file },
210 { "login", Int, &make_login_shell, (char **)0x0 },
211 { "noediting", Int, &no_line_editing, (char **)0x0 },
212 { "noprofile", Int, &no_profile, (char **)0x0 },
213 { "norc", Int, &no_rc, (char **)0x0 },
214 { "posix", Int, &posixly_correct, (char **)0x0 },
215 { "rcfile", Charp, (int *)0x0, &bashrc_file },
216 #if defined (RESTRICTED_SHELL)
217 { "restricted", Int, &restricted, (char **)0x0 },
219 { "verbose", Int, &echo_input_at_read, (char **)0x0 },
220 { "version", Int, &do_version, (char **)0x0 },
221 { "wordexp", Int, &wordexp_only, (char **)0x0 },
222 { (char *)0x0, Int, (int *)0x0, (char **)0x0 }
225 /* These are extern so execute_simple_command can set them, and then
226 longjmp back to main to execute a shell script, instead of calling
227 main () again and resulting in indefinite, possibly fatal, stack
229 procenv_t subshell_top_level;
231 char **subshell_argv;
232 char **subshell_envp;
234 #if defined (BUFFERED_INPUT)
235 /* The file descriptor from which the shell is reading input. */
236 int default_buffered_input = -1;
239 /* The following two variables are not static so they can show up in $-. */
240 int read_from_stdin; /* -s flag supplied */
241 int want_pending_command; /* -c flag supplied */
243 static int shell_reinitialized = 0;
244 static char *local_pending_command;
246 static FILE *default_input;
248 static STRING_INT_ALIST *shopt_alist;
249 static int shopt_ind = 0, shopt_len = 0;
251 static int parse_long_options __P((char **, int, int));
252 static int parse_shell_options __P((char **, int, int));
253 static int bind_args __P((char **, int, int, int));
255 static void add_shopt_to_alist __P((char *, int));
256 static void run_shopt_alist __P((void));
258 static void execute_env_file __P((char *));
259 static void run_startup_files __P((void));
260 static int open_shell_script __P((char *));
261 static void set_bash_input __P((void));
262 static int run_one_command __P((char *));
263 static int run_wordexp __P((char *));
265 static int uidget __P((void));
266 static int isnetconn __P((int));
268 static void init_interactive __P((void));
269 static void init_noninteractive __P((void));
271 static void set_shell_name __P((char *));
272 static void shell_initialize __P((void));
273 static void shell_reinitialize __P((void));
275 static void show_shell_usage __P((FILE *, int));
279 _cygwin32_check_tmp ()
283 if (stat ("/tmp", &sb) < 0)
284 internal_warning ("could not find /tmp, please create!");
287 if (S_ISDIR (sb.st_mode) == 0)
288 internal_warning ("/tmp must be a valid directory name");
291 #endif /* __CYGWIN__ */
293 #if defined (NO_MAIN_ENV_ARG)
294 /* systems without third argument to main() */
299 #else /* !NO_MAIN_ENV_ARG */
301 main (argc, argv, env)
304 #endif /* !NO_MAIN_ENV_ARG */
307 int code, old_errexit_flag;
308 #if defined (RESTRICTED_SHELL)
311 volatile int locally_skip_execution;
312 volatile int arg_index, top_level_arg_index;
317 #endif /* __OPENNT */
323 USE_VAR(old_errexit_flag);
324 #if defined (RESTRICTED_SHELL)
328 /* Catch early SIGINTs. */
329 code = setjmp (top_level);
333 #if defined (USING_BASH_MALLOC) && defined (DEBUG)
334 # if 0 /* memory tracing */
339 malloc_set_register (1);
346 _cygwin32_check_tmp ();
347 #endif /* __CYGWIN__ */
349 /* Wait forever if we are debugging a login shell. */
350 while (debugging_login_shell);
352 set_default_locale ();
354 running_setuid = uidget ();
356 if (getenv ("POSIXLY_CORRECT") || getenv ("POSIX_PEDANTIC"))
359 #if defined (USE_GNU_MALLOC_LIBRARY)
360 mcheck (programming_error, (void (*) ())0);
361 #endif /* USE_GNU_MALLOC_LIBRARY */
363 if (setjmp (subshell_top_level))
365 argc = subshell_argc;
366 argv = subshell_argv;
371 shell_reinitialized = 0;
373 /* Initialize `local' variables for all `invocations' of main (). */
375 local_pending_command = (char *)NULL;
376 want_pending_command = locally_skip_execution = read_from_stdin = 0;
377 default_input = stdin;
378 #if defined (BUFFERED_INPUT)
379 default_buffered_input = -1;
382 /* Fix for the `infinite process creation' bug when running shell scripts
383 from startup files on System V. */
384 login_shell = make_login_shell = 0;
386 /* If this shell has already been run, then reinitialize it to a
388 if (shell_initialized || shell_name)
390 /* Make sure that we do not infinitely recurse as a login shell. */
391 if (*shell_name == '-')
394 shell_reinitialize ();
395 if (setjmp (top_level))
399 shell_environment = env;
400 set_shell_name (argv[0]);
401 shell_start_time = NOW; /* NOW now defined in general.h */
403 /* Parse argument flags from the input line. */
405 /* Find full word arguments first. */
406 arg_index = parse_long_options (argv, arg_index, argc);
408 if (want_initial_help)
410 show_shell_usage (stdout, 1);
411 exit (EXECUTION_SUCCESS);
416 show_shell_version (1);
417 exit (EXECUTION_SUCCESS);
420 /* If user supplied the "--login" flag, then set and invert LOGIN_SHELL. */
421 if (make_login_shell)
424 login_shell = -login_shell;
427 set_login_shell (login_shell != 0);
429 /* All done with full word options; do standard shell option parsing.*/
430 this_command_name = shell_name; /* for error reporting */
431 arg_index = parse_shell_options (argv, arg_index, argc);
434 dump_translatable_strings = 1;
436 if (dump_translatable_strings)
437 read_but_dont_execute = 1;
439 if (running_setuid && privileged_mode == 0)
440 disable_priv_mode ();
442 /* Need to get the argument to a -c option processed in the
443 above loop. The next arg is a command to execute, and the
444 following args are $0...$n respectively. */
445 if (want_pending_command)
447 local_pending_command = argv[arg_index];
448 if (local_pending_command == 0)
450 report_error ("option `-c' requires an argument");
455 this_command_name = (char *)NULL;
457 /* First, let the outside world know about our interactive status.
458 A shell is interactive if the `-i' flag was given, or if all of
459 the following conditions are met:
461 no arguments remaining or the -s flag given
462 standard input is a terminal
463 standard output is a terminal
464 Refer to Posix.2, the description of the `sh' utility. */
466 if (forced_interactive || /* -i flag */
467 (!local_pending_command && /* No -c command and ... */
468 wordexp_only == 0 && /* No --wordexp and ... */
469 ((arg_index == argc) || /* no remaining args or... */
470 read_from_stdin) && /* -s flag with args, and */
471 isatty (fileno (stdin)) && /* Input is a terminal and */
472 isatty (fileno (stdout)))) /* output is a terminal. */
475 init_noninteractive ();
477 #define CLOSE_FDS_AT_LOGIN
478 #if defined (CLOSE_FDS_AT_LOGIN)
480 * Some systems have the bad habit of starting login shells with lots of open
481 * file descriptors. For instance, most systems that have picked up the
482 * pre-4.0 Sun YP code leave a file descriptor open each time you call one
483 * of the getpw* functions, and it's set to be open across execs. That
484 * means one for login, one for xterm, one for shelltool, etc.
486 if (login_shell && interactive_shell)
488 for (i = 3; i < 20; i++)
491 #endif /* CLOSE_FDS_AT_LOGIN */
493 /* If we're in a strict Posix.2 mode, turn on interactive comments and
494 other Posix.2 things. */
497 bind_variable ("POSIXLY_CORRECT", "y");
498 sv_strict_posix ("POSIXLY_CORRECT");
501 /* Now we run the shopt_alist and process the options. */
505 /* From here on in, the shell must be a normal functioning shell.
506 Variables from the environment are expected to be set, etc. */
509 set_default_locale_vars ();
511 if (interactive_shell)
515 term = getenv ("TERM");
516 no_line_editing |= term && (STREQ (term, "emacs"));
517 term = getenv ("EMACS");
518 running_under_emacs = term ? ((strmatch ("*term*", term, 0) == 0) ? 2 : 1)
522 top_level_arg_index = arg_index;
523 old_errexit_flag = exit_immediately_on_error;
525 /* Give this shell a place to longjmp to before executing the
526 startup files. This allows users to press C-c to abort the
528 code = setjmp (top_level);
531 if (code == EXITPROG)
532 exit_shell (last_command_exit_value);
535 #if defined (JOB_CONTROL)
536 /* Reset job control, since run_startup_files turned it off. */
537 set_job_control (interactive_shell);
539 /* Reset value of `set -e', since it's turned off before running
540 the startup files. */
541 exit_immediately_on_error += old_errexit_flag;
542 locally_skip_execution++;
546 arg_index = top_level_arg_index;
548 /* Execute the start-up scripts. */
550 if (interactive_shell == 0)
552 makunbound ("PS1", shell_variables);
553 makunbound ("PS2", shell_variables);
555 expand_aliases = posixly_correct;
559 change_flag ('i', FLAG_ON);
563 #if defined (RESTRICTED_SHELL)
564 /* Set restricted_shell based on whether the basename of $0 indicates that
565 the shell should be restricted or if the `-r' option was supplied at
567 restricted_shell = shell_is_restricted (shell_name);
569 /* If the `-r' option is supplied at invocation, make sure that the shell
570 is not in restricted mode when running the startup files. */
571 saverst = restricted;
575 /* The startup files are run with `set -e' temporarily disabled. */
576 if (locally_skip_execution == 0 && running_setuid == 0)
578 old_errexit_flag = exit_immediately_on_error;
579 exit_immediately_on_error = 0;
581 run_startup_files ();
582 exit_immediately_on_error += old_errexit_flag;
585 /* If we are invoked as `sh', turn on Posix mode. */
588 bind_variable ("POSIXLY_CORRECT", "y");
589 sv_strict_posix ("POSIXLY_CORRECT");
592 #if defined (RESTRICTED_SHELL)
593 /* Turn on the restrictions after executing the startup files. This
594 means that `bash -r' or `set -r' invoked from a startup file will
595 turn on the restrictions after the startup files are executed. */
596 restricted = saverst || restricted;
597 if (shell_reinitialized == 0)
598 maybe_make_restricted (shell_name);
599 #endif /* RESTRICTED_SHELL */
604 last_command_exit_value = run_wordexp (argv[arg_index]);
605 exit_shell (last_command_exit_value);
608 if (local_pending_command)
610 arg_index = bind_args (argv, arg_index, argc, 0);
612 #if defined (ONESHOT)
614 run_one_command (local_pending_command);
615 exit_shell (last_command_exit_value);
617 with_input_from_string (local_pending_command, "-c");
618 goto read_and_execute;
619 #endif /* !ONESHOT */
622 /* Get possible input filename and set up default_buffered_input or
623 default_input as appropriate. */
624 if (arg_index != argc && read_from_stdin == 0)
626 open_shell_script (argv[arg_index]);
629 else if (interactive == 0)
630 /* In this mode, bash is reading a script from stdin, which is a
631 pipe or redirected file. */
632 #if defined (BUFFERED_INPUT)
633 default_buffered_input = fileno (stdin); /* == 0 */
635 setbuf (default_input, (char *)NULL);
636 #endif /* !BUFFERED_INPUT */
640 /* Bind remaining args to $1 ... $n */
641 arg_index = bind_args (argv, arg_index, argc, 1);
642 /* Do the things that should be done only for interactive shells. */
643 if (interactive_shell)
645 /* Set up for checking for presence of mail. */
646 remember_mail_dates ();
649 #if defined (HISTORY)
650 /* Initialize the interactive history stuff. */
651 bash_initialize_history ();
652 if (shell_initialized == 0)
656 /* Initialize terminal state for interactive shells after the
657 .bash_profile and .bashrc are interpreted. */
661 #if !defined (ONESHOT)
663 #endif /* !ONESHOT */
665 shell_initialized = 1;
667 /* Read commands until exit condition. */
669 exit_shell (last_command_exit_value);
673 parse_long_options (argv, arg_start, arg_end)
675 int arg_start, arg_end;
677 int arg_index, longarg, i;
680 arg_index = arg_start;
681 while ((arg_index != arg_end) && (arg_string = argv[arg_index]) &&
682 (*arg_string == '-'))
686 /* Make --login equivalent to -login. */
687 if (arg_string[1] == '-' && arg_string[2])
693 for (i = 0; long_args[i].name; i++)
695 if (STREQ (arg_string + 1, long_args[i].name))
697 if (long_args[i].type == Int)
698 *long_args[i].int_value = 1;
699 else if (argv[++arg_index] == 0)
701 report_error ("option `%s' requires an argument",
706 *long_args[i].char_value = argv[arg_index];
711 if (long_args[i].name == 0)
715 report_error ("%s: unrecognized option", argv[arg_index]);
716 show_shell_usage (stderr, 0);
719 break; /* No such argument. Maybe flag arg. */
729 parse_shell_options (argv, arg_start, arg_end)
731 int arg_start, arg_end;
734 int arg_character, on_or_off, next_arg, i;
735 char *o_option, *arg_string;
737 arg_index = arg_start;
738 while (arg_index != arg_end && (arg_string = argv[arg_index]) &&
739 (*arg_string == '-' || *arg_string == '+'))
741 /* There are flag arguments, so parse them. */
742 next_arg = arg_index + 1;
744 /* A single `-' signals the end of options. From the 4.3 BSD sh.
745 An option `--' means the same thing; this is the standard
746 getopt(3) meaning. */
747 if (arg_string[0] == '-' &&
748 (arg_string[1] == '\0' ||
749 (arg_string[1] == '-' && arg_string[2] == '\0')))
753 on_or_off = arg_string[0];
754 while (arg_character = arg_string[i++])
756 switch (arg_character)
759 want_pending_command = 1;
767 o_option = argv[next_arg];
770 list_minus_o_opts (-1, (on_or_off == '-') ? 0 : 1);
773 if (set_minus_o_option (on_or_off, o_option) != EXECUTION_SUCCESS)
779 /* Since some of these can be overridden by the normal
780 interactive/non-interactive shell initialization or
781 initializing posix mode, we save the options and process
782 them after initialization. */
783 o_option = argv[next_arg];
786 shopt_listopt (o_option, (on_or_off == '-') ? 0 : 1);
789 add_shopt_to_alist (o_option, on_or_off);
794 dump_translatable_strings = 1;
798 if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
800 report_error ("%c%c: unrecognized option", on_or_off, arg_character);
801 show_shell_usage (stderr, 0);
806 /* Can't do just a simple increment anymore -- what about
807 "bash -abouo emacs ignoreeof -hP"? */
808 arg_index = next_arg;
814 /* Exit the shell with status S. */
819 /* Do trap[0] if defined. Allow it to override the exit status
821 if (signal_is_trapped (0))
822 s = run_exit_trap ();
824 #if defined (PROCESS_SUBSTITUTION)
826 #endif /* PROCESS_SUBSTITUTION */
828 #if defined (HISTORY)
829 if (interactive_shell)
830 maybe_save_shell_history ();
833 #if defined (JOB_CONTROL)
834 /* If the user has run `shopt -s huponexit', hangup all jobs when we exit
835 an interactive login shell. ksh does this unconditionally. */
836 if (interactive_shell && login_shell && hup_on_exit)
839 /* If this shell is interactive, terminate all stopped jobs and
840 restore the original terminal process group. Don't do this if we're
841 in a subshell and calling exit_shell after, for example, a failed
843 if (subshell_environment == 0)
845 #endif /* JOB_CONTROL */
847 /* Always return the exit status of the last command to our parent. */
851 #ifdef INCLUDE_UNUSED
852 /* A wrapper for exit that (optionally) can do other things, like malloc
853 statistics tracing. */
862 /* Source the bash startup files. If POSIXLY_CORRECT is non-zero, we obey
863 the Posix.2 startup file rules: $ENV is expanded, and if the file it
864 names exists, that file is sourced. The Posix.2 rules are in effect
865 for interactive shells only. (section 4.56.5.3) */
867 /* Execute ~/.bashrc for most shells. Never execute it if
868 ACT_LIKE_SH is set, or if NO_RC is set.
870 If the executable file "/usr/gnu/src/bash/foo" contains:
877 COMMAND EXECUTE BASHRC
878 --------------------------------
882 rsh machine ls YES (for rsh, which calls `bash -c')
883 rsh machine foo YES (for shell started by rsh) NO (for foo!)
890 execute_env_file (env_file)
895 if (env_file && *env_file)
897 fn = expand_string_unsplit_to_string (env_file, Q_DOUBLE_QUOTES);
899 maybe_execute_file (fn, 1);
907 #if defined (JOB_CONTROL)
910 int sourced_login, run_by_ssh;
912 /* get the rshd/sshd case out of the way first. */
913 if (interactive_shell == 0 && no_rc == 0 && login_shell == 0 &&
914 act_like_sh == 0 && local_pending_command)
916 #ifdef SSH_SOURCE_BASHRC
917 run_by_ssh = (find_variable ("SSH_CLIENT") != (SHELL_VAR *)0) ||
918 (find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0);
923 /* If we were run by sshd or we think we were run by rshd, execute
924 ~/.bashrc if we are a top-level shell. */
925 if ((run_by_ssh || isnetconn (fileno (stdin))) && shell_level < 2)
928 # if defined (__OPENNT)
929 maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
931 maybe_execute_file (SYS_BASHRC, 1);
934 maybe_execute_file (bashrc_file, 1);
939 #if defined (JOB_CONTROL)
940 /* Startup files should be run without job control enabled. */
941 old_job_control = interactive_shell ? set_job_control (0) : 0;
946 /* A shell begun with the --login flag that is not in posix mode runs
947 the login shell startup files, no matter whether or not it is
948 interactive. If NON_INTERACTIVE_LOGIN_SHELLS is defined, run the
949 startup files if argv[0][0] == '-' as well. */
950 #if defined (NON_INTERACTIVE_LOGIN_SHELLS)
951 if (login_shell && posixly_correct == 0)
953 if (login_shell < 0 && posixly_correct == 0)
956 /* We don't execute .bashrc for login shells. */
959 /* Execute /etc/profile and one of the personal login shell
960 initialization files. */
963 maybe_execute_file (SYS_PROFILE, 1);
965 if (act_like_sh) /* sh */
966 maybe_execute_file ("~/.profile", 1);
967 else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
968 (maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
969 maybe_execute_file ("~/.profile", 1);
975 /* A non-interactive shell not named `sh' and not in posix mode reads and
976 executes commands from $BASH_ENV. If `su' starts a shell with `-c cmd'
977 and `-su' as the name of the shell, we want to read the startup files.
978 No other non-interactive shells read any startup files. */
979 if (interactive_shell == 0 && !(su_shell && login_shell))
981 if (posixly_correct == 0 && act_like_sh == 0 && privileged_mode == 0 &&
983 execute_env_file (get_string_value ("BASH_ENV"));
987 /* Interactive shell or `-su' shell. */
988 if (posixly_correct == 0) /* bash, sh */
990 if (login_shell && sourced_login++ == 0)
992 /* We don't execute .bashrc for login shells. */
995 /* Execute /etc/profile and one of the personal login shell
996 initialization files. */
999 maybe_execute_file (SYS_PROFILE, 1);
1001 if (act_like_sh) /* sh */
1002 maybe_execute_file ("~/.profile", 1);
1003 else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
1004 (maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
1005 maybe_execute_file ("~/.profile", 1);
1010 if (act_like_sh == 0 && no_rc == 0)
1013 # if defined (__OPENNT)
1014 maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
1016 maybe_execute_file (SYS_BASHRC, 1);
1019 maybe_execute_file (bashrc_file, 1);
1022 else if (act_like_sh && privileged_mode == 0 && sourced_env++ == 0)
1023 execute_env_file (get_string_value ("ENV"));
1025 else /* bash --posix, sh --posix */
1028 if (interactive_shell && privileged_mode == 0 && sourced_env++ == 0)
1029 execute_env_file (get_string_value ("ENV"));
1032 #if defined (JOB_CONTROL)
1033 set_job_control (old_job_control);
1037 #if defined (RESTRICTED_SHELL)
1038 /* Return 1 if the shell should be a restricted one based on NAME or the
1039 value of `restricted'. Don't actually do anything, just return a
1042 shell_is_restricted (name)
1049 temp = base_pathname (name);
1050 return (STREQ (temp, RESTRICTED_SHELL_NAME));
1053 /* Perhaps make this shell a `restricted' one, based on NAME. If the
1054 basename of NAME is "rbash", then this shell is restricted. The
1055 name of the restricted shell is a configurable option, see config.h.
1056 In a restricted shell, PATH, SHELL, ENV, and BASH_ENV are read-only
1058 Do this also if `restricted' is already set to 1; maybe the shell was
1061 maybe_make_restricted (name)
1066 temp = base_pathname (shell_name);
1067 if (restricted || (STREQ (temp, RESTRICTED_SHELL_NAME)))
1069 set_var_read_only ("PATH");
1070 set_var_read_only ("SHELL");
1071 set_var_read_only ("ENV");
1072 set_var_read_only ("BASH_ENV");
1075 return (restricted);
1077 #endif /* RESTRICTED_SHELL */
1079 /* Fetch the current set of uids and gids and return 1 if we're running
1080 setuid or setgid. */
1087 if (current_user.uid != u)
1089 FREE (current_user.user_name);
1090 FREE (current_user.shell);
1091 FREE (current_user.home_dir);
1092 current_user.user_name = current_user.shell = current_user.home_dir = (char *)NULL;
1094 current_user.uid = u;
1095 current_user.gid = getgid ();
1096 current_user.euid = geteuid ();
1097 current_user.egid = getegid ();
1099 /* See whether or not we are running setuid or setgid. */
1100 return (current_user.uid != current_user.euid) ||
1101 (current_user.gid != current_user.egid);
1105 disable_priv_mode ()
1107 setuid (current_user.uid);
1108 setgid (current_user.gid);
1109 current_user.euid = current_user.uid;
1110 current_user.egid = current_user.gid;
1118 WORD_LIST *wl, *result;
1120 code = setjmp (top_level);
1122 if (code != NOT_JUMPED)
1126 /* Some kind of throw to top_level has occured. */
1128 return last_command_exit_value = 127;
1130 return last_command_exit_value;
1132 return last_command_exit_value = 1;
1134 command_error ("run_wordexp", CMDERR_BADJUMP, code, 0);
1138 /* Run it through the parser to get a list of words and expand them */
1139 if (words && *words)
1141 with_input_from_string (words, "--wordexp");
1142 if (parse_command () != 0)
1144 if (global_command == 0)
1149 if (global_command->type != cm_simple)
1151 wl = global_command->value.Simple->words;
1152 result = wl ? expand_words_no_vars (wl) : (WORD_LIST *)0;
1155 result = (WORD_LIST *)0;
1157 last_command_exit_value = 0;
1165 /* Count up the number of words and bytes, and print them. Don't count
1166 the trailing NUL byte. */
1167 for (nw = nb = 0, wl = result; wl; wl = wl->next)
1170 nb += strlen (wl->word->word);
1172 printf ("%u\n%u\n", nw, nb);
1173 /* Print each word on a separate line. This will have to be changed when
1174 the interface to glibc is completed. */
1175 for (wl = result; wl; wl = wl->next)
1176 printf ("%s\n", wl->word->word);
1181 #if defined (ONESHOT)
1182 /* Run one command, given as the argument to the -c option. Tell
1183 parse_and_execute not to fork for a simple command. */
1185 run_one_command (command)
1190 code = setjmp (top_level);
1192 if (code != NOT_JUMPED)
1194 #if defined (PROCESS_SUBSTITUTION)
1195 unlink_fifo_list ();
1196 #endif /* PROCESS_SUBSTITUTION */
1199 /* Some kind of throw to top_level has occured. */
1201 return last_command_exit_value = 127;
1203 return last_command_exit_value;
1205 return last_command_exit_value = 1;
1207 command_error ("run_one_command", CMDERR_BADJUMP, code, 0);
1210 return (parse_and_execute (savestring (command), "-c", SEVAL_NOHIST));
1212 #endif /* ONESHOT */
1215 bind_args (argv, arg_start, arg_end, start_index)
1217 int arg_start, arg_end, start_index;
1222 for (i = arg_start, args = (WORD_LIST *)NULL; i != arg_end; i++)
1223 args = make_word_list (make_word (argv[i]), args);
1226 args = REVERSE_LIST (args, WORD_LIST *);
1227 if (start_index == 0) /* bind to $0...$n for sh -c command */
1229 /* Posix.2 4.56.3 says that the first argument after sh -c command
1230 becomes $0, and the rest of the arguments become $1...$n */
1231 shell_name = savestring (args->word->word);
1232 FREE (dollar_vars[0]);
1233 dollar_vars[0] = savestring (args->word->word);
1234 remember_args (args->next, 1);
1236 else /* bind to $1...$n for shell script */
1237 remember_args (args, 1);
1239 dispose_words (args);
1248 remember_args ((WORD_LIST *)NULL, 1);
1252 open_shell_script (script_name)
1255 int fd, e, fd_is_tty;
1256 char *filename, *path_filename;
1261 free (dollar_vars[0]);
1262 dollar_vars[0] = savestring (script_name);
1263 filename = savestring (script_name);
1265 fd = open (filename, O_RDONLY);
1266 if ((fd < 0) && (errno == ENOENT) && (absolute_program (filename) == 0))
1269 /* If it's not in the current directory, try looking through PATH
1271 path_filename = find_path_file (script_name);
1275 filename = path_filename;
1276 fd = open (filename, O_RDONLY);
1285 file_error (filename);
1286 exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
1290 fd_is_tty = isatty (fd);
1295 /* Only do this with non-tty file descriptors we can seek on. */
1296 if (fd_is_tty == 0 && (lseek (fd, 0L, 1) != -1))
1298 /* Check to see if the `file' in `bash file' is a binary file
1299 according to the same tests done by execute_simple_command (),
1300 and report an error and exit if it is. */
1301 sample_len = read (fd, sample, sizeof (sample));
1305 if ((fstat (fd, &sb) == 0) && S_ISDIR (sb.st_mode))
1306 internal_error ("%s: is a directory", filename);
1310 file_error (filename);
1314 else if (sample_len > 0 && (check_binary_file (sample, sample_len)))
1316 internal_error ("%s: cannot execute binary file", filename);
1317 exit (EX_BINARY_FILE);
1319 /* Now rewind the file back to the beginning. */
1323 /* Open the script. But try to move the file descriptor to a randomly
1324 large one, in the hopes that any descriptors used by the script will
1325 not match with ours. */
1326 fd = move_to_high_fd (fd, 0, -1);
1328 #if defined (__CYGWIN__) && defined (O_TEXT)
1329 setmode (fd, O_TEXT);
1332 #if defined (BUFFERED_INPUT)
1333 default_buffered_input = fd;
1334 SET_CLOSE_ON_EXEC (default_buffered_input);
1335 #else /* !BUFFERED_INPUT */
1336 default_input = fdopen (fd, "r");
1338 if (default_input == 0)
1340 file_error (filename);
1344 SET_CLOSE_ON_EXEC (fd);
1345 if (fileno (default_input) != fd)
1346 SET_CLOSE_ON_EXEC (fileno (default_input));
1347 #endif /* !BUFFERED_INPUT */
1349 /* Just about the only way for this code to be executed is if something
1350 like `bash -i /dev/stdin' is executed. */
1351 if (interactive_shell && fd_is_tty)
1356 #if defined (BUFFERED_INPUT)
1357 default_buffered_input = 0;
1359 fclose (default_input);
1360 default_input = stdin;
1363 else if (forced_interactive && fd_is_tty == 0)
1364 /* But if a script is called with something like `bash -i scriptname',
1365 we need to do a non-interactive setup here, since we didn't do it
1367 init_noninteractive ();
1373 /* Initialize the input routines for the parser. */
1377 /* Make sure the fd from which we are reading input is not in
1379 #if defined (BUFFERED_INPUT)
1380 if (interactive == 0)
1381 sh_unset_nodelay_mode (default_buffered_input);
1383 #endif /* !BUFFERED_INPUT */
1384 sh_unset_nodelay_mode (fileno (stdin));
1386 /* with_input_from_stdin really means `with_input_from_readline' */
1387 if (interactive && no_line_editing == 0)
1388 with_input_from_stdin ();
1390 #if defined (BUFFERED_INPUT)
1392 if (interactive == 0)
1393 with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
1395 with_input_from_stream (default_input, dollar_vars[0]);
1397 #else /* !BUFFERED_INPUT */
1398 with_input_from_stream (default_input, dollar_vars[0]);
1399 #endif /* !BUFFERED_INPUT */
1402 /* Close the current shell script input source and forget about it. This is
1403 extern so execute_cmd.c:initialize_subshell() can call it. If CHECK_ZERO
1404 is non-zero, we close default_buffered_input even if it's the standard
1407 unset_bash_input (check_zero)
1410 #if defined (BUFFERED_INPUT)
1411 if ((check_zero && default_buffered_input >= 0) ||
1412 (check_zero == 0 && default_buffered_input > 0))
1414 close_buffered_fd (default_buffered_input);
1415 default_buffered_input = bash_input.location.buffered_fd = -1;
1417 #else /* !BUFFERED_INPUT */
1420 fclose (default_input);
1421 default_input = (FILE *)NULL;
1423 #endif /* !BUFFERED_INPUT */
1427 #if !defined (PROGRAM)
1428 # define PROGRAM "bash"
1432 set_shell_name (argv0)
1435 /* Here's a hack. If the name of this shell is "sh", then don't do
1436 any startup files; just try to be more like /bin/sh. */
1437 shell_name = base_pathname (argv0);
1438 if (*shell_name == '-')
1440 if (shell_name[0] == 's' && shell_name[1] == 'h' && shell_name[2] == '\0')
1442 if (shell_name[0] == 's' && shell_name[1] == 'u' && shell_name[2] == '\0')
1446 FREE (dollar_vars[0]);
1447 dollar_vars[0] = savestring (shell_name);
1449 if (*shell_name == '-')
1455 /* A program may start an interactive shell with
1456 "execl ("/bin/bash", "-", NULL)".
1457 If so, default the name of this shell to our name. */
1458 if (!shell_name || !*shell_name || (shell_name[0] == '-' && !shell_name[1]))
1459 shell_name = PROGRAM;
1465 interactive_shell = startup_state = interactive = 1;
1470 init_noninteractive ()
1472 #if defined (HISTORY)
1473 bash_history_reinit (0);
1474 #endif /* HISTORY */
1475 interactive_shell = startup_state = interactive = 0;
1477 no_line_editing = 1;
1478 #if defined (JOB_CONTROL)
1479 set_job_control (0);
1480 #endif /* JOB_CONTROL */
1484 get_current_user_info ()
1486 struct passwd *entry;
1488 /* Don't fetch this more than once. */
1489 if (current_user.user_name == 0)
1491 entry = getpwuid (current_user.uid);
1494 current_user.user_name = savestring (entry->pw_name);
1495 current_user.shell = (entry->pw_shell && entry->pw_shell[0])
1496 ? savestring (entry->pw_shell)
1497 : savestring ("/bin/sh");
1498 current_user.home_dir = savestring (entry->pw_dir);
1502 current_user.user_name = savestring ("I have no name!");
1503 current_user.shell = savestring ("/bin/sh");
1504 current_user.home_dir = savestring ("/");
1510 /* Do whatever is necessary to initialize the shell.
1511 Put new initializations in here. */
1517 /* Line buffer output for stderr and stdout. */
1518 if (shell_initialized == 0)
1520 sh_setlinebuf (stderr);
1521 sh_setlinebuf (stdout);
1524 /* Sort the array of shell builtins so that the binary search in
1525 find_shell_builtin () works correctly. */
1526 initialize_shell_builtins ();
1528 /* Initialize the trap signal handlers before installing our own
1529 signal handlers. traps.c:restore_original_signals () is responsible
1530 for restoring the original default signal handlers. That function
1531 is called when we make a new child. */
1532 initialize_traps ();
1533 initialize_signals ();
1535 /* It's highly unlikely that this will change. */
1536 if (current_host_name == 0)
1538 /* Initialize current_host_name. */
1539 if (gethostname (hostname, 255) < 0)
1540 current_host_name = "??host??";
1542 current_host_name = savestring (hostname);
1545 /* Initialize the stuff in current_user that comes from the password
1546 file. We don't need to do this right away if the shell is not
1548 if (interactive_shell)
1549 get_current_user_info ();
1551 /* Initialize our interface to the tilde expander. */
1552 tilde_initialize ();
1554 /* Initialize internal and environment variables. Don't import shell
1555 functions from the environment if we are running in privileged or
1556 restricted mode or if the shell is running setuid. */
1557 #if defined (RESTRICTED_SHELL)
1558 initialize_shell_variables (shell_environment, privileged_mode||restricted||running_setuid);
1560 initialize_shell_variables (shell_environment, privileged_mode||running_setuid);
1564 /* Initialize filename hash tables. */
1565 initialize_filename_hashing ();
1568 /* Initialize the data structures for storing and running jobs. */
1569 initialize_job_control (0);
1571 /* Initialize input streams to null. */
1572 initialize_bash_input ();
1574 /* Initialize the shell options. Don't import the shell options
1575 from the environment variable $SHELLOPTS if we are running in
1576 privileged or restricted mode or if the shell is running setuid. */
1577 #if defined (RESTRICTED_SHELL)
1578 initialize_shell_options (privileged_mode||restricted||running_setuid);
1580 initialize_shell_options (privileged_mode||running_setuid);
1584 /* Function called by main () when it appears that the shell has already
1585 had some initialization performed. This is supposed to reset the world
1586 back to a pristine state, as if we had been exec'ed. */
1588 shell_reinitialize ()
1590 /* The default shell prompts. */
1591 primary_prompt = PPROMPT;
1592 secondary_prompt = SPROMPT;
1594 /* Things that get 1. */
1595 current_command_number = 1;
1597 /* We have decided that the ~/.bashrc file should not be executed
1598 for the invocation of each shell script. If the variable $ENV
1599 (or $BASH_ENV) is set, its value is used as the name of a file
1601 no_rc = no_profile = 1;
1603 /* Things that get 0. */
1604 login_shell = make_login_shell = interactive = executing = 0;
1605 debugging = do_version = line_number = last_command_exit_value = 0;
1606 forced_interactive = interactive_shell = subshell_environment = 0;
1609 #if defined (HISTORY)
1610 bash_history_reinit (0);
1611 #endif /* HISTORY */
1613 #if defined (RESTRICTED_SHELL)
1615 #endif /* RESTRICTED_SHELL */
1617 /* Ensure that the default startup file is used. (Except that we don't
1618 execute this file for reinitialized shells). */
1619 bashrc_file = "~/.bashrc";
1621 /* Delete all variables and functions. They will be reinitialized when
1622 the environment is parsed. */
1623 delete_all_variables (shell_variables);
1624 delete_all_variables (shell_functions);
1626 shell_reinitialized = 1;
1630 show_shell_usage (fp, extra)
1635 char *set_opts, *s, *t;
1638 fprintf (fp, "GNU bash, version %s-(%s)\n", shell_version_string (), MACHTYPE);
1639 fprintf (fp, "Usage:\t%s [GNU long option] [option] ...\n\t%s [GNU long option] [option] script-file ...\n",
1640 shell_name, shell_name);
1641 fputs ("GNU long options:\n", fp);
1642 for (i = 0; long_args[i].name; i++)
1643 fprintf (fp, "\t--%s\n", long_args[i].name);
1645 fputs ("Shell options:\n", fp);
1646 fputs ("\t-irsD or -c command or -O shopt_option\t\t(invocation only)\n", fp);
1648 for (i = 0, set_opts = 0; shell_builtins[i].name; i++)
1649 if (STREQ (shell_builtins[i].name, "set"))
1650 set_opts = savestring (shell_builtins[i].short_doc);
1653 s = strchr (set_opts, '[');
1658 t = strchr (s, ']');
1661 fprintf (fp, "\t-%s or -o option\n", s);
1667 fprintf (fp, "Type `%s -c \"help set\"' for more information about shell options.\n", shell_name);
1668 fprintf (fp, "Type `%s -c help' for more information about shell builtin commands.\n", shell_name);
1669 fprintf (fp, "Use the `bashbug' command to report bugs.\n");
1674 add_shopt_to_alist (opt, on_or_off)
1678 if (shopt_ind >= shopt_len)
1681 shopt_alist = (STRING_INT_ALIST *)xrealloc (shopt_alist, shopt_len * sizeof (shopt_alist[0]));
1683 shopt_alist[shopt_ind].word = opt;
1684 shopt_alist[shopt_ind].token = on_or_off;
1693 for (i = 0; i < shopt_ind; i++)
1694 if (shopt_setopt (shopt_alist[i].word, (shopt_alist[i].token == '-')) != EXECUTION_SUCCESS)
1698 shopt_ind = shopt_len = 0;
1701 /* The second and subsequent conditions must match those used to decide
1702 whether or not to call getpeername() in isnetconn(). */
1703 #if defined (HAVE_SYS_SOCKET_H) && defined (HAVE_GETPEERNAME) && !defined (SVR4_2)
1704 # include <sys/socket.h>
1707 /* Is FD a socket or network connection? */
1712 #if defined (HAVE_GETPEERNAME) && !defined (SVR4_2) && !defined (__BEOS__)
1718 rv = getpeername(fd, &sa, &l);
1719 /* Solaris 2.5 getpeername() returns EINVAL if the fd is not a socket. */
1720 return ((rv < 0 && (errno == ENOTSOCK || errno == EINVAL)) ? 0 : 1);
1721 #else /* !HAVE_GETPEERNAME || SVR4_2 || __BEOS__ */
1722 # if defined (SVR4) || defined (SVR4_2)
1723 /* Sockets on SVR4 and SVR4.2 are character special (streams) devices. */
1728 if (fstat (fd, &sb) < 0)
1730 # if defined (S_ISFIFO)
1731 if (S_ISFIFO (sb.st_mode))
1733 # endif /* S_ISFIFO */
1734 return (S_ISCHR (sb.st_mode));
1735 # else /* !SVR4 && !SVR4_2 */
1736 # if defined (S_ISSOCK) && !defined (__BEOS__)
1739 if (fstat (fd, &sb) < 0)
1741 return (S_ISSOCK (sb.st_mode));
1742 # else /* !S_ISSOCK || __BEOS__ */
1744 # endif /* !S_ISSOCK || __BEOS__ */
1745 # endif /* !SVR4 && !SVR4_2 */
1746 #endif /* !HAVE_GETPEERNAME || SVR4_2 || __BEOS__ */