1 /* shell.c -- GNU's idea of the POSIX shell specification.
3 This file is part of Bash, the Bourne Again SHell. Bash is free
4 software; no one can prevent you from reading the source code, or
5 giving it to someone else. This file is copyrighted under the GNU
6 General Public License, which can be found in the file called
9 Copyright (C) 1988, 1991 Free Software Foundation, Inc.
11 This file is part of GNU Bash.
13 Bash is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY. No author or distributor accepts responsibility to
15 anyone for the consequences of using it or for whether it serves
16 any particular purpose or works at all, unless he says so in
17 writing. Refer to the GNU Emacs General Public License for full
20 Everyone is granted permission to copy, modify and redistribute
21 Bash, but only under the conditions described in the GNU General
22 Public License. A copy of this license is supposed to have been
23 given to you along with GNU Emacs so you can know your rights and
24 responsibilities. It should be in a file named COPYING.
26 Among other things, the copyright notice and this notice must be
27 preserved on all copies.
30 Sunday, January 10th, 1988.
31 Initial author: Brian Fox
33 #define INSTALL_DEBUG_MODE
37 #include "bashtypes.h"
39 # include <sys/file.h>
41 #include "posixstat.h"
49 #if defined (HAVE_UNISTD_H)
56 #include "mailcheck.h"
58 #include "builtins/common.h"
60 #if defined (JOB_CONTROL)
62 #endif /* JOB_CONTROL */
65 #include "execute_cmd.h"
69 # include "bashhist.h"
70 # include <readline/history.h>
73 #include <tilde/tilde.h>
74 #include <glob/fnmatch.h>
76 #if !defined (HAVE_GETPW_DECLS)
77 extern struct passwd *getpwuid ();
78 #endif /* !HAVE_GETPW_DECLS */
84 extern char *dist_version, *release_status;
85 extern int patch_level, build_version;
86 extern int subshell_environment;
87 extern int last_command_exit_value;
88 extern int line_number;
89 extern char *primary_prompt, *secondary_prompt;
90 extern int expand_aliases;
91 extern char *this_command_name;
92 extern int array_needs_making;
94 /* Non-zero means that this shell has already been run; i.e. you should
95 call shell_reinitialize () if you need to start afresh. */
96 int shell_initialized = 0;
98 COMMAND *global_command = (COMMAND *)NULL;
100 /* Information about the current user. */
101 struct user_info current_user =
103 -1, -1, -1, -1, (char *)NULL, (char *)NULL, (char *)NULL
106 /* The current host's name. */
107 char *current_host_name = (char *)NULL;
109 /* Non-zero means that this shell is a login shell.
112 1 = login shell from getty (or equivalent fake out)
113 -1 = login shell from "-login" flag.
114 -2 = both from getty, and from flag.
118 /* Non-zero means that at this moment, the shell is interactive. In
119 general, this means that the shell is at this moment reading input
120 from the keyboard. */
123 /* Non-zero means that the shell was started as an interactive shell. */
124 int interactive_shell = 0;
126 /* Non-zero means to send a SIGHUP to all jobs when an interactive login
130 /* Tells what state the shell was in when it started:
131 0 = non-interactive shell script
134 This is a superset of the information provided by interactive_shell.
136 int startup_state = 0;
138 /* Special debugging helper. */
139 int debugging_login_shell = 0;
141 /* The environment that the shell passes to other commands. */
142 char **shell_environment;
144 /* Non-zero when we are executing a top-level command. */
147 /* The number of commands executed so far. */
148 int current_command_number = 1;
150 /* Non-zero is the recursion depth for commands. */
151 int indirection_level = 0;
153 /* The name of this shell, as taken from argv[0]. */
154 char *shell_name = (char *)NULL;
156 /* time in seconds when the shell was started */
157 time_t shell_start_time;
159 /* Are we running in an emacs shell window? */
160 int running_under_emacs;
162 /* The name of the .(shell)rc file. */
163 static char *bashrc_file = "~/.bashrc";
165 /* Non-zero means to act more like the Bourne shell on startup. */
166 static int act_like_sh;
168 /* Non-zero if this shell is being run by `su'. */
171 /* Non-zero if we have already expanded and sourced $ENV. */
172 static int sourced_env;
174 /* Is this shell running setuid? */
175 static int running_setuid;
177 /* Values for the long-winded argument names. */
178 static int debugging; /* Do debugging things. */
179 static int no_rc; /* Don't execute ~/.bashrc */
180 static int no_profile; /* Don't execute .profile */
181 static int do_version; /* Display interesting version info. */
182 static int make_login_shell; /* Make this shell be a `-bash' shell. */
183 static int want_initial_help; /* --help option */
185 int no_line_editing = 0; /* Don't do fancy line editing. */
186 int posixly_correct = 0; /* Non-zero means posix.2 superset. */
187 int dump_translatable_strings; /* Dump strings in $"...", don't execute. */
188 int dump_po_strings; /* Dump strings in $"..." in po format */
189 int wordexp_only = 0; /* Do word expansion only */
191 /* Some long-winded argument names. These are obviously new. */
200 { "debug", Int, &debugging, (char **)0x0 },
201 { "dump-po-strings", Int, &dump_po_strings, (char **)0x0 },
202 { "dump-strings", Int, &dump_translatable_strings, (char **)0x0 },
203 { "help", Int, &want_initial_help, (char **)0x0 },
204 { "login", Int, &make_login_shell, (char **)0x0 },
205 { "noediting", Int, &no_line_editing, (char **)0x0 },
206 { "noprofile", Int, &no_profile, (char **)0x0 },
207 { "norc", Int, &no_rc, (char **)0x0 },
208 { "posix", Int, &posixly_correct, (char **)0x0 },
209 { "rcfile", Charp, (int *)0x0, &bashrc_file },
210 #if defined (RESTRICTED_SHELL)
211 { "restricted", Int, &restricted, (char **)0x0 },
213 { "verbose", Int, &echo_input_at_read, (char **)0x0 },
214 { "version", Int, &do_version, (char **)0x0 },
215 { "wordexp", Int, &wordexp_only, (char **)0x0 },
216 { (char *)0x0, Int, (int *)0x0, (char **)0x0 }
219 /* These are extern so execute_simple_command can set them, and then
220 longjmp back to main to execute a shell script, instead of calling
221 main () again and resulting in indefinite, possibly fatal, stack
223 procenv_t subshell_top_level;
225 char **subshell_argv;
226 char **subshell_envp;
228 #if defined (BUFFERED_INPUT)
229 /* The file descriptor from which the shell is reading input. */
230 int default_buffered_input = -1;
233 static int read_from_stdin; /* -s flag supplied */
234 static int want_pending_command; /* -c flag supplied */
235 static char *local_pending_command;
237 static FILE *default_input;
239 static int parse_long_options ();
240 static int parse_shell_options ();
241 static void run_startup_files ();
242 static int bind_args ();
243 static int open_shell_script ();
244 static void set_bash_input ();
245 static int run_one_command ();
246 static int run_wordexp ();
248 static int uidget ();
249 static int isnetconn ();
251 static void init_interactive (), init_noninteractive ();
252 static void set_shell_name ();
253 static void shell_initialize ();
254 static void shell_reinitialize ();
256 static void show_shell_usage ();
260 _cygwin32_check_tmp ()
264 if (stat ("/tmp", &sb) < 0)
265 internal_warning ("could not find /tmp, please create!");
268 if (S_ISDIR (sb.st_mode) == 0)
269 internal_warning ("/tmp must be a valid directory name");
272 #endif /* __CYGWIN32__ */
275 main (argc, argv, env)
281 volatile int locally_skip_execution;
282 volatile int arg_index, top_level_arg_index;
284 /* Catch early SIGINTs. */
285 code = setjmp (top_level);
292 _cygwin32_check_tmp ();
295 /* Wait forever if we are debugging a login shell. */
296 while (debugging_login_shell);
298 set_default_locale ();
300 running_setuid = uidget ();
302 posixly_correct = (getenv ("POSIXLY_CORRECT") != (char *)NULL) ||
303 (getenv ("POSIX_PEDANTIC") != (char *)NULL);
305 #if defined (USE_GNU_MALLOC_LIBRARY)
306 mcheck (programming_error, (void (*) ())0);
307 #endif /* USE_GNU_MALLOC_LIBRARY */
309 if (setjmp (subshell_top_level))
311 argc = subshell_argc;
312 argv = subshell_argv;
317 /* Initialize `local' variables for all `invocations' of main (). */
319 local_pending_command = (char *)NULL;
320 want_pending_command = locally_skip_execution = read_from_stdin = 0;
321 default_input = stdin;
322 #if defined (BUFFERED_INPUT)
323 default_buffered_input = -1;
326 /* Fix for the `infinite process creation' bug when running shell scripts
327 from startup files on System V. */
328 login_shell = make_login_shell = 0;
330 /* If this shell has already been run, then reinitialize it to a
332 if (shell_initialized || shell_name)
334 /* Make sure that we do not infinitely recurse as a login shell. */
335 if (*shell_name == '-')
338 shell_reinitialize ();
339 if (setjmp (top_level))
343 shell_environment = env;
344 set_shell_name (argv[0]);
345 shell_start_time = NOW; /* NOW now defined in general.h */
347 /* Parse argument flags from the input line. */
349 /* Find full word arguments first. */
350 arg_index = parse_long_options (argv, arg_index, argc);
352 if (want_initial_help)
354 show_shell_usage (stdout, 1);
355 exit (EXECUTION_SUCCESS);
360 show_shell_version (1);
361 exit (EXECUTION_SUCCESS);
364 /* If user supplied the "--login" flag, then set and invert LOGIN_SHELL. */
365 if (make_login_shell)
368 login_shell = -login_shell;
371 /* All done with full word options; do standard shell option parsing.*/
372 this_command_name = shell_name; /* for error reporting */
373 arg_index = parse_shell_options (argv, arg_index, argc);
376 dump_translatable_strings = 1;
378 if (dump_translatable_strings)
379 read_but_dont_execute = 1;
381 if (running_setuid && privileged_mode == 0)
382 disable_priv_mode ();
384 /* Need to get the argument to a -c option processed in the
385 above loop. The next arg is a command to execute, and the
386 following args are $0...$n respectively. */
387 if (want_pending_command)
389 local_pending_command = argv[arg_index];
390 if (local_pending_command == 0)
392 report_error ("option `-c' requires an argument");
397 this_command_name = (char *)NULL;
399 /* First, let the outside world know about our interactive status.
400 A shell is interactive if the `-i' flag was given, or if all of
401 the following conditions are met:
403 no arguments remaining or the -s flag given
404 standard input is a terminal
405 standard output is a terminal
406 Refer to Posix.2, the description of the `sh' utility. */
408 if (forced_interactive || /* -i flag */
409 (!local_pending_command && /* No -c command and ... */
410 wordexp_only == 0 && /* No --wordexp and ... */
411 ((arg_index == argc) || /* no remaining args or... */
412 read_from_stdin) && /* -s flag with args, and */
413 isatty (fileno (stdin)) && /* Input is a terminal and */
414 isatty (fileno (stdout)))) /* output is a terminal. */
417 init_noninteractive ();
419 #define CLOSE_FDS_AT_LOGIN
420 #if defined (CLOSE_FDS_AT_LOGIN)
422 * Some systems have the bad habit of starting login shells with lots of open
423 * file descriptors. For instance, most systems that have picked up the
424 * pre-4.0 Sun YP code leave a file descriptor open each time you call one
425 * of the getpw* functions, and it's set to be open across execs. That
426 * means one for login, one for xterm, one for shelltool, etc.
428 if (login_shell && interactive_shell)
430 for (i = 3; i < 20; i++)
433 #endif /* CLOSE_FDS_AT_LOGIN */
435 /* If we're in a strict Posix.2 mode, turn on interactive comments and
436 other Posix.2 things. */
439 posix_initialize (posixly_correct);
440 #if defined (READLINE)
441 if (interactive_shell)
442 posix_readline_initialize (posixly_correct);
446 /* From here on in, the shell must be a normal functioning shell.
447 Variables from the environment are expected to be set, etc. */
450 set_default_locale_vars ();
452 if (interactive_shell)
456 term = getenv ("TERM");
457 no_line_editing |= term && (STREQ (term, "emacs"));
458 term = getenv ("EMACS");
459 running_under_emacs = term ? ((fnmatch ("*term*", term, 0) == 0) ? 2 : 1)
463 top_level_arg_index = arg_index;
465 /* Give this shell a place to longjmp to before executing the
466 startup files. This allows users to press C-c to abort the
468 code = setjmp (top_level);
471 if (code == EXITPROG)
472 exit_shell (last_command_exit_value);
475 #if defined (JOB_CONTROL)
476 /* Reset job control, since run_startup_files turned it off. */
477 set_job_control (interactive_shell);
479 locally_skip_execution++;
483 arg_index = top_level_arg_index;
485 /* Execute the start-up scripts. */
487 if (interactive_shell == 0)
489 makunbound ("PS1", shell_variables);
490 makunbound ("PS2", shell_variables);
491 interactive = expand_aliases = 0;
495 change_flag ('i', FLAG_ON);
499 #if defined (RESTRICTED_SHELL)
500 /* If the `-r' option is supplied at invocation, make sure that the shell
501 is not in restricted mode when running the startup files. */
502 saverst = restricted;
506 if (locally_skip_execution == 0 && running_setuid == 0)
507 run_startup_files ();
509 /* If we are invoked as `sh', turn on Posix mode. */
512 posix_initialize (posixly_correct = 1);
513 #if defined (READLINE)
514 if (interactive_shell)
515 posix_readline_initialize (posixly_correct);
519 #if defined (RESTRICTED_SHELL)
520 /* Turn on the restrictions after executing the startup files. This
521 means that `bash -r' or `set -r' invoked from a startup file will
522 turn on the restrictions after the startup files are executed. */
523 restricted = saverst || restricted;
524 maybe_make_restricted (shell_name);
525 #endif /* RESTRICTED_SHELL */
530 last_command_exit_value = run_wordexp (argv[arg_index]);
531 exit_shell (last_command_exit_value);
534 if (local_pending_command)
536 arg_index = bind_args (argv, arg_index, argc, 0);
539 #if defined (ONESHOT)
540 run_one_command (local_pending_command);
541 exit_shell (last_command_exit_value);
543 with_input_from_string (local_pending_command, "-c");
544 goto read_and_execute;
545 #endif /* !ONESHOT */
548 /* Get possible input filename and set up default_buffered_input or
549 default_input as appropriate. */
550 if (arg_index != argc && read_from_stdin == 0)
552 open_shell_script (argv[arg_index]);
555 else if (interactive == 0)
556 /* In this mode, bash is reading a script from stdin, which is a
557 pipe or redirected file. */
558 #if defined (BUFFERED_INPUT)
559 default_buffered_input = fileno (stdin); /* == 0 */
561 setbuf (default_input, (char *)NULL);
562 #endif /* !BUFFERED_INPUT */
566 /* Bind remaining args to $1 ... $n */
567 arg_index = bind_args (argv, arg_index, argc, 1);
569 /* Do the things that should be done only for interactive shells. */
570 if (interactive_shell)
572 /* Set up for checking for presence of mail. */
573 remember_mail_dates ();
576 #if defined (HISTORY)
577 /* Initialize the interactive history stuff. */
578 bash_initialize_history ();
579 if (shell_initialized == 0)
583 /* Initialize terminal state for interactive shells after the
584 .bash_profile and .bashrc are interpreted. */
588 #if !defined (ONESHOT)
590 #endif /* !ONESHOT */
592 shell_initialized = 1;
594 /* Read commands until exit condition. */
596 exit_shell (last_command_exit_value);
600 parse_long_options (argv, arg_start, arg_end)
602 int arg_start, arg_end;
604 int arg_index, longarg, i;
607 arg_index = arg_start;
608 while ((arg_index != arg_end) && (arg_string = argv[arg_index]) &&
609 (*arg_string == '-'))
613 /* Make --login equivalent to -login. */
614 if (arg_string[1] == '-' && arg_string[2])
620 for (i = 0; long_args[i].name; i++)
622 if (STREQ (arg_string + 1, long_args[i].name))
624 if (long_args[i].type == Int)
625 *long_args[i].int_value = 1;
626 else if (argv[++arg_index] == 0)
628 report_error ("option `%s' requires an argument",
633 *long_args[i].char_value = argv[arg_index];
638 if (long_args[i].name == 0)
642 report_error ("%s: unrecognized option", argv[arg_index]);
643 show_shell_usage (stderr, 0);
646 break; /* No such argument. Maybe flag arg. */
656 parse_shell_options (argv, arg_start, arg_end)
658 int arg_start, arg_end;
661 int arg_character, on_or_off, next_arg, i;
662 char *o_option, *arg_string;
664 arg_index = arg_start;
665 while (arg_index != arg_end && (arg_string = argv[arg_index]) &&
666 (*arg_string == '-' || *arg_string == '+'))
668 /* There are flag arguments, so parse them. */
669 next_arg = arg_index + 1;
671 /* A single `-' signals the end of options. From the 4.3 BSD sh.
672 An option `--' means the same thing; this is the standard
673 getopt(3) meaning. */
674 if (arg_string[0] == '-' &&
675 (arg_string[1] == '\0' ||
676 (arg_string[1] == '-' && arg_string[2] == '\0')))
680 on_or_off = arg_string[0];
681 while (arg_character = arg_string[i++])
683 switch (arg_character)
686 want_pending_command = 1;
694 o_option = argv[next_arg];
697 list_minus_o_opts (-1, (on_or_off == '-') ? 0 : 1);
700 if (set_minus_o_option (on_or_off, o_option) != EXECUTION_SUCCESS)
706 dump_translatable_strings = 1;
710 if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
712 report_error ("%c%c: unrecognized option", on_or_off, arg_character);
713 show_shell_usage (stderr, 0);
718 /* Can't do just a simple increment anymore -- what about
719 "bash -abouo emacs ignoreeof -hP"? */
720 arg_index = next_arg;
726 /* Exit the shell with status S. */
731 /* Do trap[0] if defined. Allow it to override the exit status
733 if (signal_is_trapped (0))
734 s = run_exit_trap ();
736 #if defined (PROCESS_SUBSTITUTION)
738 #endif /* PROCESS_SUBSTITUTION */
740 #if defined (HISTORY)
741 if (interactive_shell)
742 maybe_save_shell_history ();
745 #if defined (JOB_CONTROL)
746 /* If the user has run `shopt -s huponexit', hangup all jobs when we exit
747 an interactive login shell. ksh does this unconditionally. */
748 if (interactive_shell && login_shell && hup_on_exit)
751 /* If this shell is interactive, terminate all stopped jobs and
752 restore the original terminal process group. */
754 #endif /* JOB_CONTROL */
756 /* Always return the exit status of the last command to our parent. */
760 /* Source the bash startup files. If POSIXLY_CORRECT is non-zero, we obey
761 the Posix.2 startup file rules: $ENV is expanded, and if the file it
762 names exists, that file is sourced. The Posix.2 rules are in effect
763 for interactive shells only. (section 4.56.5.3) */
765 /* Execute ~/.bashrc for most shells. Never execute it if
766 ACT_LIKE_SH is set, or if NO_RC is set.
768 If the executable file "/usr/gnu/src/bash/foo" contains:
775 COMMAND EXECUTE BASHRC
776 --------------------------------
780 rsh machine ls YES (for rsh, which calls `bash -c')
781 rsh machine foo YES (for shell started by rsh) NO (for foo!)
788 execute_env_file (env_file)
794 if (env_file && *env_file)
796 list = expand_string_unsplit (env_file, Q_DOUBLE_QUOTES);
799 fn = string_list (list);
800 dispose_words (list);
803 maybe_execute_file (fn, 1);
812 #if defined (JOB_CONTROL)
815 int sourced_login, run_by_ssh;
818 /* get the rshd/sshd case out of the way first. */
819 if (interactive_shell == 0 && no_rc == 0 && login_shell == 0 &&
820 act_like_sh == 0 && local_pending_command)
822 /* Find out if we were invoked by ssh. If so, set RUN_BY_SSH to 1. */
823 sshvar = find_variable ("SSH_CLIENT");
827 /* Now that we've tested the variable, we need to unexport it. */
828 sshvar->attributes &= ~att_exported;
829 array_needs_making = 1;
834 /* If we were run by sshd or we think we were run by rshd, execute
836 if (run_by_ssh || isnetconn (fileno (stdin)))
839 maybe_execute_file (SYS_BASHRC, 1);
841 maybe_execute_file (bashrc_file, 1);
846 #if defined (JOB_CONTROL)
847 /* Startup files should be run without job control enabled. */
848 old_job_control = interactive_shell ? set_job_control (0) : 0;
853 #if defined (NON_INTERACTIVE_LOGIN_SHELLS)
856 /* We don't execute .bashrc for login shells. */
859 /* Execute /etc/profile and one of the personal login shell
860 initialization files. */
863 maybe_execute_file (SYS_PROFILE, 1);
865 if (act_like_sh) /* sh */
866 maybe_execute_file ("~/.profile", 1);
867 else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
868 (maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
869 maybe_execute_file ("~/.profile", 1);
874 #endif /* NON_INTERACTIVE_LOGIN_SHELLS */
876 /* A non-interactive shell not named `sh' and not in posix mode reads and
877 executes commands from $BASH_ENV. If `su' starts a shell with `-c cmd'
878 and `-su' as the name of the shell, we want to read the startup files.
879 No other non-interactive shells read any startup files. */
880 if (interactive_shell == 0 && !(su_shell && login_shell))
882 if (posixly_correct == 0 && act_like_sh == 0 && privileged_mode == 0 &&
884 execute_env_file (get_string_value ("BASH_ENV"));
888 /* Interactive shell or `-su' shell. */
889 if (posixly_correct == 0) /* bash, sh */
891 if (login_shell && sourced_login++ == 0)
893 /* We don't execute .bashrc for login shells. */
896 /* Execute /etc/profile and one of the personal login shell
897 initialization files. */
900 maybe_execute_file (SYS_PROFILE, 1);
902 if (act_like_sh) /* sh */
903 maybe_execute_file ("~/.profile", 1);
904 else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
905 (maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
906 maybe_execute_file ("~/.profile", 1);
911 if (act_like_sh == 0 && no_rc == 0)
914 maybe_execute_file (SYS_BASHRC, 1);
916 maybe_execute_file (bashrc_file, 1);
919 else if (act_like_sh && privileged_mode == 0 && sourced_env++ == 0)
920 execute_env_file (get_string_value ("ENV"));
922 else /* bash --posix, sh --posix */
925 if (interactive_shell && privileged_mode == 0 && sourced_env++ == 0)
926 execute_env_file (get_string_value ("ENV"));
929 #if defined (JOB_CONTROL)
930 set_job_control (old_job_control);
934 #if defined (RESTRICTED_SHELL)
935 /* Perhaps make this shell a `restricted' one, based on NAME. If the
936 basename of NAME is "rbash", then this shell is restricted. The
937 name of the restricted shell is a configurable option, see config.h.
938 In a restricted shell, PATH and SHELL are read-only and non-unsettable.
939 Do this also if `restricted' is already set to 1; maybe the shell was
942 maybe_make_restricted (name)
947 temp = base_pathname (shell_name);
948 if (restricted || (STREQ (temp, RESTRICTED_SHELL_NAME)))
950 set_var_read_only ("PATH");
951 set_var_read_only ("SHELL");
956 #endif /* RESTRICTED_SHELL */
958 /* Fetch the current set of uids and gids and return 1 if we're running
966 if (current_user.uid != u)
968 FREE (current_user.user_name);
969 FREE (current_user.shell);
970 FREE (current_user.home_dir);
971 current_user.user_name = current_user.shell = current_user.home_dir = (char *)NULL;
973 current_user.uid = u;
974 current_user.gid = getgid ();
975 current_user.euid = geteuid ();
976 current_user.egid = getegid ();
978 /* See whether or not we are running setuid or setgid. */
979 return (current_user.uid != current_user.euid) ||
980 (current_user.gid != current_user.egid);
986 setuid (current_user.uid);
987 setgid (current_user.gid);
988 current_user.euid = current_user.uid;
989 current_user.egid = current_user.gid;
998 WORD_LIST *wl, *result;
1000 code = setjmp (top_level);
1002 if (code != NOT_JUMPED)
1006 /* Some kind of throw to top_level has occured. */
1008 return last_command_exit_value = 127;
1010 return last_command_exit_value;
1012 return last_command_exit_value = 1;
1014 programming_error ("run_wordexp: bad jump: code %d", code);
1018 /* Run it through the parser to get a list of words and expand them */
1019 if (words && *words)
1021 with_input_from_string (words, "--wordexp");
1022 if (parse_command () != 0)
1024 if (global_command == 0)
1029 if (global_command->type != cm_simple)
1031 wl = global_command->value.Simple->words;
1032 result = wl ? expand_words_no_vars (wl) : (WORD_LIST *)0;
1035 result = (WORD_LIST *)0;
1037 last_command_exit_value = 0;
1045 /* Count up the number of words and bytes, and print them. Don't count
1046 the trailing NUL byte. */
1047 for (nw = nb = 0, wl = result; wl; wl = wl->next)
1050 nb += strlen (wl->word->word);
1052 printf ("%u\n%u\n", nw, nb);
1053 /* Print each word on a separate line. This will have to be changed when
1054 the interface to glibc is completed. */
1055 for (wl = result; wl; wl = wl->next)
1056 printf ("%s\n", wl->word->word);
1061 #if defined (ONESHOT)
1062 /* Run one command, given as the argument to the -c option. Tell
1063 parse_and_execute not to fork for a simple command. */
1065 run_one_command (command)
1070 code = setjmp (top_level);
1072 if (code != NOT_JUMPED)
1074 #if defined (PROCESS_SUBSTITUTION)
1075 unlink_fifo_list ();
1076 #endif /* PROCESS_SUBSTITUTION */
1079 /* Some kind of throw to top_level has occured. */
1081 return last_command_exit_value = 127;
1083 return last_command_exit_value;
1085 return last_command_exit_value = 1;
1087 programming_error ("run_one_command: bad jump: code %d", code);
1090 return (parse_and_execute (savestring (command), "-c", SEVAL_NOHIST));
1092 #endif /* ONESHOT */
1095 bind_args (argv, arg_start, arg_end, start_index)
1097 int arg_start, arg_end, start_index;
1102 for (i = arg_start, args = (WORD_LIST *)NULL; i != arg_end; i++)
1103 args = make_word_list (make_word (argv[i]), args);
1106 args = REVERSE_LIST (args, WORD_LIST *);
1107 if (start_index == 0) /* bind to $0...$n for sh -c command */
1109 /* Posix.2 4.56.3 says that the first argument after sh -c command
1110 becomes $0, and the rest of the arguments become $1...$n */
1111 shell_name = savestring (args->word->word);
1112 FREE (dollar_vars[0]);
1113 dollar_vars[0] = savestring (args->word->word);
1114 remember_args (args->next, 1);
1116 else /* bind to $1...$n for shell script */
1117 remember_args (args, 1);
1119 dispose_words (args);
1128 remember_args ((WORD_LIST *)NULL, 1);
1132 open_shell_script (script_name)
1136 char *filename, *path_filename;
1137 unsigned char sample[80];
1141 free (dollar_vars[0]);
1142 dollar_vars[0] = savestring (script_name);
1143 filename = savestring (script_name);
1145 fd = open (filename, O_RDONLY);
1146 if ((fd < 0) && (errno == ENOENT) && (absolute_program (filename) == 0))
1149 /* If it's not in the current directory, try looking through PATH
1151 path_filename = find_path_file (script_name);
1155 filename = path_filename;
1156 fd = open (filename, O_RDONLY);
1165 file_error (filename);
1166 exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
1169 /* Only do this with file descriptors we can seek on. */
1170 if (lseek (fd, 0L, 1) != -1)
1172 /* Check to see if the `file' in `bash file' is a binary file
1173 according to the same tests done by execute_simple_command (),
1174 and report an error and exit if it is. */
1175 sample_len = read (fd, sample, sizeof (sample));
1179 if ((fstat (fd, &sb) == 0) && S_ISDIR (sb.st_mode))
1180 internal_error ("%s: is a directory", filename);
1184 file_error (filename);
1188 else if (sample_len > 0 && (check_binary_file (sample, sample_len)))
1190 internal_error ("%s: cannot execute binary file", filename);
1191 exit (EX_BINARY_FILE);
1193 /* Now rewind the file back to the beginning. */
1197 #if defined (BUFFERED_INPUT)
1198 default_buffered_input = fd;
1200 /* This is never executed. */
1201 if (default_buffered_input == -1)
1203 file_error (filename);
1207 SET_CLOSE_ON_EXEC (default_buffered_input);
1208 #else /* !BUFFERED_INPUT */
1209 /* Open the script. But try to move the file descriptor to a randomly
1210 large one, in the hopes that any descriptors used by the script will
1211 not match with ours. */
1212 fd = move_to_high_fd (fd, 0, -1);
1214 default_input = fdopen (fd, "r");
1216 if (default_input == 0)
1218 file_error (filename);
1222 SET_CLOSE_ON_EXEC (fd);
1223 if (fileno (default_input) != fd)
1224 SET_CLOSE_ON_EXEC (fileno (default_input));
1225 #endif /* !BUFFERED_INPUT */
1227 if (interactive_shell == 0 || isatty (fd) == 0)
1228 /* XXX - does this really need to be called again here? */
1229 init_noninteractive ();
1232 /* I don't believe that this code is ever executed, even in
1233 the presence of /dev/fd. */
1237 #if defined (BUFFERED_INPUT)
1238 default_buffered_input = 0;
1240 fclose (default_input);
1241 default_input = stdin;
1248 /* Initialize the input routines for the parser. */
1252 /* Make sure the fd from which we are reading input is not in
1254 #if defined (BUFFERED_INPUT)
1255 if (interactive == 0)
1256 unset_nodelay_mode (default_buffered_input);
1258 #endif /* !BUFFERED_INPUT */
1259 unset_nodelay_mode (fileno (stdin));
1261 /* with_input_from_stdin really means `with_input_from_readline' */
1262 if (interactive && no_line_editing == 0)
1263 with_input_from_stdin ();
1265 #if defined (BUFFERED_INPUT)
1267 if (interactive == 0)
1268 with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
1270 with_input_from_stream (default_input, dollar_vars[0]);
1272 #else /* !BUFFERED_INPUT */
1273 with_input_from_stream (default_input, dollar_vars[0]);
1274 #endif /* !BUFFERED_INPUT */
1277 /* Close the current shell script input source and forget about it. This is
1278 extern so execute_cmd.c:initialize_subshell() can call it. If CHECK_ZERO
1279 is non-zero, we close default_buffered_input even if it's the standard
1282 unset_bash_input (check_zero)
1285 #if defined (BUFFERED_INPUT)
1286 if ((check_zero && default_buffered_input >= 0) ||
1287 (check_zero == 0 && default_buffered_input > 0))
1289 close_buffered_fd (default_buffered_input);
1290 default_buffered_input = bash_input.location.buffered_fd = -1;
1292 #else /* !BUFFERED_INPUT */
1295 fclose (default_input);
1296 default_input = (FILE *)NULL;
1298 #endif /* !BUFFERED_INPUT */
1302 #if !defined (PROGRAM)
1303 # define PROGRAM "bash"
1307 set_shell_name (argv0)
1310 /* Here's a hack. If the name of this shell is "sh", then don't do
1311 any startup files; just try to be more like /bin/sh. */
1312 shell_name = base_pathname (argv0);
1313 if (*shell_name == '-')
1315 if (shell_name[0] == 's' && shell_name[1] == 'h' && shell_name[2] == '\0')
1317 if (shell_name[0] == 's' && shell_name[1] == 'u' && shell_name[2] == '\0')
1321 FREE (dollar_vars[0]);
1322 dollar_vars[0] = savestring (shell_name);
1324 if (*shell_name == '-')
1330 /* A program may start an interactive shell with
1331 "execl ("/bin/bash", "-", NULL)".
1332 If so, default the name of this shell to our name. */
1333 if (!shell_name || !*shell_name || (shell_name[0] == '-' && !shell_name[1]))
1334 shell_name = PROGRAM;
1340 interactive_shell = startup_state = interactive = 1;
1345 init_noninteractive ()
1347 #if defined (HISTORY)
1348 bash_history_reinit (0);
1349 #endif /* HISTORY */
1350 interactive_shell = startup_state = interactive = 0;
1352 no_line_editing = 1;
1353 #if defined (JOB_CONTROL)
1354 set_job_control (0);
1355 #endif /* JOB_CONTROL */
1359 get_current_user_info ()
1361 struct passwd *entry;
1363 /* Don't fetch this more than once. */
1364 if (current_user.user_name == 0)
1366 entry = getpwuid (current_user.uid);
1369 current_user.user_name = savestring (entry->pw_name);
1370 current_user.shell = (entry->pw_shell && entry->pw_shell[0])
1371 ? savestring (entry->pw_shell)
1372 : savestring ("/bin/sh");
1373 current_user.home_dir = savestring (entry->pw_dir);
1377 current_user.user_name = savestring ("I have no name!");
1378 current_user.shell = savestring ("/bin/sh");
1379 current_user.home_dir = savestring ("/");
1385 /* Do whatever is necessary to initialize the shell.
1386 Put new initializations in here. */
1392 /* Line buffer output for stderr and stdout. */
1393 #if defined (SunOS5)
1394 if (shell_initialized == 0)
1397 setlinebuf (stderr);
1398 setlinebuf (stdout);
1401 /* Sort the array of shell builtins so that the binary search in
1402 find_shell_builtin () works correctly. */
1403 initialize_shell_builtins ();
1405 /* Initialize the trap signal handlers before installing our own
1406 signal handlers. traps.c:restore_original_signals () is responsible
1407 for restoring the original default signal handlers. That function
1408 is called when we make a new child. */
1409 initialize_traps ();
1410 initialize_signals ();
1412 /* It's highly unlikely that this will change. */
1413 if (current_host_name == 0)
1415 /* Initialize current_host_name. */
1416 if (gethostname (hostname, 255) < 0)
1417 current_host_name = "??host??";
1419 current_host_name = savestring (hostname);
1422 /* Initialize the stuff in current_user that comes from the password
1423 file. We don't need to do this right away if the shell is not
1425 if (interactive_shell)
1426 get_current_user_info ();
1428 /* Initialize our interface to the tilde expander. */
1429 tilde_initialize ();
1431 /* Initialize internal and environment variables. Don't import shell
1432 functions from the environment if we are running in privileged or
1433 restricted mode or if the shell is running setuid. */
1434 #if defined (RESTRICTED_SHELL)
1435 initialize_shell_variables (shell_environment, privileged_mode||restricted||running_setuid);
1437 initialize_shell_variables (shell_environment, privileged_mode||running_setuid);
1441 /* Initialize filename hash tables. */
1442 initialize_filename_hashing ();
1445 /* Initialize the data structures for storing and running jobs. */
1446 initialize_job_control (0);
1448 /* Initialize input streams to null. */
1449 initialize_bash_input ();
1451 /* Initialize the shell options. Don't import the shell options
1452 from the environment variable $SHELLOPTS if we are running in
1453 privileged or restricted mode or if the shell is running setuid. */
1454 #if defined (RESTRICTED_SHELL)
1455 initialize_shell_options (privileged_mode||restricted||running_setuid);
1457 initialize_shell_options (privileged_mode||running_setuid);
1461 /* Function called by main () when it appears that the shell has already
1462 had some initialization performed. This is supposed to reset the world
1463 back to a pristine state, as if we had been exec'ed. */
1465 shell_reinitialize ()
1467 /* The default shell prompts. */
1468 primary_prompt = PPROMPT;
1469 secondary_prompt = SPROMPT;
1471 /* Things that get 1. */
1472 current_command_number = 1;
1474 /* We have decided that the ~/.bashrc file should not be executed
1475 for the invocation of each shell script. If the variable $ENV
1476 (or $BASH_ENV) is set, its value is used as the name of a file
1478 no_rc = no_profile = 1;
1480 /* Things that get 0. */
1481 login_shell = make_login_shell = interactive = executing = 0;
1482 debugging = do_version = line_number = last_command_exit_value = 0;
1483 forced_interactive = interactive_shell = subshell_environment = 0;
1486 #if defined (HISTORY)
1487 bash_history_reinit (0);
1488 #endif /* HISTORY */
1490 #if defined (RESTRICTED_SHELL)
1492 #endif /* RESTRICTED_SHELL */
1494 /* Ensure that the default startup file is used. (Except that we don't
1495 execute this file for reinitialized shells). */
1496 bashrc_file = "~/.bashrc";
1498 /* Delete all variables and functions. They will be reinitialized when
1499 the environment is parsed. */
1500 delete_all_variables (shell_variables);
1501 delete_all_variables (shell_functions);
1504 /* Pretend the PATH variable has changed. */
1505 flush_hashed_filenames ();
1510 show_shell_usage (fp, extra)
1515 char *set_opts, *s, *t;
1518 fprintf (fp, "GNU bash, version %s-(%s)\n", shell_version_string (), MACHTYPE);
1519 fprintf (fp, "Usage:\t%s [GNU long option] [option] ...\n\t%s [GNU long option] [option] script-file ...\n",
1520 shell_name, shell_name);
1521 fputs ("GNU long options:\n", fp);
1522 for (i = 0; long_args[i].name; i++)
1523 fprintf (fp, "\t--%s\n", long_args[i].name);
1525 fputs ("Shell options:\n", fp);
1526 fputs ("\t-irsD or -c command\t\t(invocation only)\n", fp);
1528 for (i = 0, set_opts = 0; shell_builtins[i].name; i++)
1529 if (STREQ (shell_builtins[i].name, "set"))
1530 set_opts = savestring (shell_builtins[i].short_doc);
1533 s = strchr (set_opts, '[');
1538 t = strchr (s, ']');
1541 fprintf (fp, "\t-%s or -o option\n", s);
1547 fprintf (fp, "Type `%s -c \"help set\"' for more information about shell options.\n", shell_name);
1548 fprintf (fp, "Type `%s -c help' for more information about shell builtin commands.\n", shell_name);
1549 fprintf (fp, "Use the `bashbug' command to report bugs.\n");
1553 /* The second and subsequent conditions must match those used to decide
1554 whether or not to call getpeername() in isnetconn(). */
1555 #if defined (HAVE_SYS_SOCKET_H) && defined (HAVE_GETPEERNAME) && !defined (SVR4_2)
1556 # include <sys/socket.h>
1559 /* Is FD a socket or network connection? */
1564 #if defined (HAVE_GETPEERNAME) && !defined (SVR4_2)
1569 rv = getpeername(fd, &sa, &l);
1570 /* Solaris 2.5 getpeername() returns EINVAL if the fd is not a socket. */
1571 return ((rv < 0 && (errno == ENOTSOCK || errno == EINVAL)) ? 0 : 1);
1572 #else /* !HAVE_GETPEERNAME || SVR4_2 */
1573 # if defined (SVR4) || defined (SVR4_2)
1574 /* Sockets on SVR4 and SVR4.2 are character special (streams) devices. */
1579 if (fstat (fd, &sb) < 0)
1581 # if defined (S_ISFIFO)
1582 if (S_ISFIFO (sb.st_mode))
1584 # endif /* S_ISFIFO */
1585 return (S_ISCHR (sb.st_mode));
1586 # else /* !SVR4 && !SVR4_2 */
1587 # if defined (S_ISSOCK)
1590 if (fstat (fd, &sb) < 0)
1592 return (S_ISSOCK (sb.st_mode));
1593 # else /* !S_ISSOCK */
1595 # endif /* !S_ISSOCK */
1596 # endif /* !SVR4 && !SVR4_2 */
1597 #endif /* !HAVE_GETPEERNAME || SVR4_2 */