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
35 #include "bashtypes.h"
42 #include "posixstat.h"
45 #if defined (HAVE_VARARGS_H)
52 #if defined (JOB_CONTROL)
54 #endif /* JOB_CONTROL */
57 #include "execute_cmd.h"
60 # include "bashhist.h"
61 # include <readline/history.h>
64 #include <tilde/tilde.h>
66 #if defined (USG) && !defined (HAVE_GETPW_DECLS)
67 extern struct passwd
*getpwuid ();
68 #endif /* USG && !HAVE_GETPW_DECLS */
75 extern char *dist_version
;
76 extern int patch_level
, build_version
;
77 extern int subshell_environment
; /* Found in execute_cmd.c. */
78 extern int last_command_exit_value
;
79 extern int return_catch_flag
;
80 extern jmp_buf return_catch
;
81 extern int need_here_doc
, current_command_line_count
, line_number
;
82 extern char *ps1_prompt
, **prompt_string_pointer
;
83 extern int loop_level
, continuing
, breaking
;
84 extern int parse_and_execute_level
;
85 extern char *this_command_name
;
87 /* Non-zero means that this shell has already been run; i.e. you should
88 call shell_reinitialize () if you need to start afresh. */
89 static int shell_initialized
= 0;
90 static int sourced_env
= 0;
92 /* The current maintainer of the shell. You change this in the
94 #if !defined (MAINTAINER)
95 #define MAINTAINER "bash-maintainers@prep.ai.mit.edu"
98 char *the_current_maintainer
= MAINTAINER
;
100 char *primary_prompt
= PPROMPT
;
101 char *secondary_prompt
= SPROMPT
;
103 COMMAND
*global_command
= (COMMAND
*)NULL
;
105 /* Non-zero after SIGINT. */
106 int interrupt_state
= 0;
108 /* Information about the current user. */
109 struct user_info current_user
=
111 -1, -1, -1, -1, (char *)NULL
, (char *)NULL
, (char *)NULL
114 /* The current host's name. */
115 char *current_host_name
= (char *)NULL
;
117 /* Non-zero means that this shell is a login shell.
120 1 = login shell from getty (or equivalent fake out)
121 -1 = login shell from "-login" flag.
122 -2 = both from getty, and from flag.
126 /* Non-zero means that at this moment, the shell is interactive. In
127 general, this means that the shell is at this moment reading input
128 from the keyboard. */
131 /* Non-zero means that the shell was started as an interactive shell. */
132 int interactive_shell
= 0;
134 /* Tells what state the shell was in when it started:
135 0 = non-interactive shell script
138 This is a superset of the information provided by interactive_shell.
140 int startup_state
= 0;
142 /* Special debugging helper. */
143 int debugging_login_shell
= 0;
145 /* The environment that the shell passes to other commands. */
146 char **shell_environment
;
148 /* Non-zero when we are executing a top-level command. */
151 /* The number of commands executed so far. */
152 int current_command_number
= 1;
154 /* The environment at the top-level REP loop. We use this in the case of
156 jmp_buf top_level
, catch;
158 #if defined (JOB_CONTROL) || defined (_POSIX_VERSION)
159 /* The signal masks that this shell runs with. */
160 sigset_t top_level_mask
;
161 #endif /* JOB_CONTROL */
163 /* Non-zero is the recursion depth for commands. */
164 int indirection_level
= 0;
166 /* The number of times BASH has been executed. This is set
167 by initialize_variables () in variables.c. */
170 /* The name of this shell, as taken from argv[0]. */
171 char *shell_name
= (char *)NULL
;
173 /* time in seconds when the shell was started */
174 time_t shell_start_time
;
176 /* The name of the .(shell)rc file. */
177 static char *bashrc_file
= "~/.bashrc";
179 /* Non-zero means to act more like the Bourne shell on startup. */
180 static int act_like_sh
= 0;
182 /* Values for the long-winded argument names. */
183 static int debugging
= 0; /* Do debugging things. */
184 static int no_rc
= 0; /* Don't execute ~/.bashrc */
185 static int no_profile
= 0; /* Don't execute .profile */
186 static int do_version
= 0; /* Display interesting version info. */
187 static int quiet
= 0; /* Be quiet when starting up. */
188 static int make_login_shell
= 0; /* Make this shell be a `-bash' shell. */
190 int no_line_editing
= 0; /* Don't do fancy line editing. */
191 int no_brace_expansion
= 0; /* Non-zero means no foo{a,b} -> fooa foob. */
193 int posixly_correct
= 0; /* Non-zero means posix.2 superset. */
195 /* Some long-winded argument names. These are obviously new. */
204 { "debug", Int
, &debugging
, (char **)0x0 },
205 { "norc", Int
, &no_rc
, (char **)0x0 },
206 { "noprofile", Int
, &no_profile
, (char **)0x0 },
207 { "rcfile", Charp
, (int *)0x0, &bashrc_file
},
208 { "version", Int
, &do_version
, (char **)0x0 },
209 { "quiet", Int
, &quiet
, (char **)0x0 },
210 { "login", Int
, &make_login_shell
, (char **)0x0 },
211 { "nolineediting", Int
, &no_line_editing
, (char **)0x0 },
212 { "nobraceexpansion", Int
, &no_brace_expansion
, (char **)0x0 },
213 { "posix", Int
, &posixly_correct
, (char **)0x0 },
214 { (char *)0x0, Int
, (int *)0x0, (char **)0x0 }
217 /* These are extern so execute_simple_command can set them, and then
218 longjmp back to main to execute a shell script, instead of calling
219 main () again and resulting in indefinite, possibly fatal, stack
221 jmp_buf subshell_top_level
;
223 char **subshell_argv
;
224 char **subshell_envp
;
226 #if defined (BUFFERED_INPUT)
227 /* The file descriptor from which the shell is reading input. */
228 int default_buffered_input
= -1;
231 static int want_pending_command
;
232 static char *local_pending_command
;
234 static int isnetconn ();
235 static void run_startup_files ();
237 static void shell_initialize ();
238 static void shell_reinitialize ();
239 static void initialize_signals ();
240 static void initialize_terminating_signals ();
242 main (argc
, argv
, env
)
247 int arg_index
, locally_skip_execution
;
248 int top_level_arg_index
, read_from_stdin
;
251 /* There is a bug in the NeXT 2.1 rlogind that causes opens
252 of /dev/tty to fail. */
253 #if defined (RLOGIN_PGRP_BUG)
257 tty_fd
= open ("/dev/tty", O_RDWR
);
262 tty
= (char *)ttyname (fileno (stdin
));
263 tty_fd
= open (tty
, O_RDWR
);
267 #endif /* RLOGIN_PGRP_BUG */
269 /* Wait forever if we are debugging a login shell. */
270 while (debugging_login_shell
);
272 current_user
.uid
= getuid ();
273 current_user
.gid
= getgid ();
274 current_user
.euid
= geteuid ();
275 current_user
.egid
= getegid ();
277 /* See whether or not we are running setuid or setgid. */
278 privileged_mode
= (current_user
.uid
!= current_user
.euid
) ||
279 (current_user
.gid
!= current_user
.egid
);
281 posixly_correct
= (getenv ("POSIXLY_CORRECT") != (char *)NULL
) ||
282 (getenv ("POSIX_PEDANTIC") != (char *)NULL
);
284 #if defined (USE_GNU_MALLOC_LIBRARY)
285 mcheck (programming_error
, (void (*) ())0);
286 #endif /* USE_GNU_MALLOC_LIBRARY */
288 if (setjmp (subshell_top_level
))
290 argc
= subshell_argc
;
291 argv
= subshell_argv
;
296 /* Initialize local variables for all `invocations' of main (). */
298 local_pending_command
= (char *)NULL
;
299 want_pending_command
= 0;
300 locally_skip_execution
= 0;
302 default_input
= stdin
;
303 #if defined (BUFFERED_INPUT)
304 default_buffered_input
= -1;
307 /* Fix for the `infinite process creation' bug when running shell scripts
308 from startup files on System V. */
309 login_shell
= make_login_shell
= 0;
311 /* If this shell has already been run, then reinitialize it to a
313 if (shell_initialized
|| shell_name
)
315 /* Make sure that we do not infinitely recurse as a login shell. */
316 if (*shell_name
== '-')
319 shell_reinitialize ();
320 if (setjmp (top_level
))
324 /* Here's a hack. If the name of this shell is "sh", then don't do
325 any startup files; just try to be more like /bin/sh. */
326 /* XXX - next version - make this be the same as -posix. */
327 shell_name
= base_pathname (argv
[0]);
328 if (*shell_name
== '-')
330 if (shell_name
[0] == 's' && shell_name
[1] == 'h' && !shell_name
[2])
335 shell_environment
= env
;
336 shell_name
= argv
[0];
337 dollar_vars
[0] = savestring (shell_name
);
339 if (*shell_name
== '-')
345 #if defined (JOB_CONTROL)
347 job_control
= 0; /* XXX - not posix */
348 #endif /* JOB_CONTROL */
350 shell_start_time
= NOW
; /* NOW now defined in general.h */
352 /* A program may start an interactive shell with
353 "execl ("/bin/bash", "-", NULL)".
354 If so, default the name of this shell to our name. */
355 if (!shell_name
|| !*shell_name
|| (shell_name
[0] == '-' && !shell_name
[1]))
358 /* Parse argument flags from the input line. */
360 /* Find full word arguments first. */
361 while ((arg_index
!= argc
) && *(argv
[arg_index
]) == '-')
363 for (i
= 0; long_args
[i
].name
; i
++)
365 if (STREQ (&(argv
[arg_index
][1]), long_args
[i
].name
))
367 if (long_args
[i
].type
== Int
)
368 *long_args
[i
].int_value
= 1;
371 if (!argv
[++arg_index
])
373 report_error ("option `%s' expected an argument",
378 *long_args
[i
].char_value
= argv
[arg_index
];
380 goto handle_next_arg
;
383 break; /* No such argument. Maybe flag arg. */
388 /* If we're in a strict Posix.2 mode, turn on interactive comments. */
390 interactive_comments
= 1;
392 /* If user supplied the "-login" flag, then set and invert LOGIN_SHELL. */
393 if (make_login_shell
)
396 login_shell
= -login_shell
;
399 /* All done with full word options; do standard shell option parsing.*/
400 this_command_name
= shell_name
; /* for error reporting */
401 while (arg_index
!= argc
&& argv
[arg_index
] &&
402 (*argv
[arg_index
] == '-' || *argv
[arg_index
] == '+'))
404 /* There are flag arguments, so parse them. */
405 int arg_character
, on_or_off
, next_arg
;
406 char *o_option
, *arg_string
;
409 next_arg
= arg_index
+ 1;
410 arg_string
= argv
[arg_index
];
411 on_or_off
= arg_string
[0];
413 /* A single `-' signals the end of options. From the 4.3 BSD sh.
414 An option `--' means the same thing; this is the standard
415 getopt(3) meaning. */
416 if (arg_string
[0] == '-' &&
417 (arg_string
[1] == '\0' ||
418 (arg_string
[1] == '-' && arg_string
[2] == '\0')))
424 while (arg_character
= arg_string
[i
++])
426 switch (arg_character
)
429 want_pending_command
= 1;
437 o_option
= argv
[next_arg
];
440 list_minus_o_opts ();
443 if (set_minus_o_option (on_or_off
, o_option
) != EXECUTION_SUCCESS
)
449 if (change_flag (arg_character
, on_or_off
) == FLAG_ERROR
)
451 report_error ("%c%c: bad option", on_or_off
, arg_character
);
457 /* Can't do just a simple increment anymore -- what about
458 "bash -abouo emacs ignoreeof -hP"? */
459 arg_index
= next_arg
;
462 /* Need to get the argument to a -c option processed in the
463 above loop. The next arg is a command to execute, and the
464 following args are $0...$n respectively. */
465 if (want_pending_command
)
467 local_pending_command
= argv
[arg_index
];
468 if (!local_pending_command
)
470 report_error ("`-c' requires an argument");
475 this_command_name
= (char *)NULL
;
477 /* First, let the outside world know about our interactive status.
478 A shell is interactive if the `-i' flag was given, or if all of
479 the following conditions are met:
481 no arguments remaining or the -s flag given
482 standard input is a terminal
483 standard output is a terminal
484 Refer to Posix.2, the description of the `sh' utility. */
486 if (forced_interactive
|| /* -i flag */
487 (!local_pending_command
&& /* No -c command and ... */
488 ((arg_index
== argc
) || /* no remaining args or... */
489 read_from_stdin
) && /* -s flag with args, and */
490 isatty (fileno (stdin
)) && /* Input is a terminal and */
491 isatty (fileno (stdout
)))) /* output is a terminal. */
493 interactive_shell
= startup_state
= interactive
= 1;
497 #if defined (HISTORY)
498 # if defined (BANG_HISTORY)
499 history_expansion
= 0;
501 remember_on_history
= 0;
503 interactive_shell
= startup_state
= interactive
= 0;
505 #if defined (JOB_CONTROL)
507 #endif /* JOB_CONTROL */
510 #define CLOSE_FDS_AT_LOGIN
511 #if defined (CLOSE_FDS_AT_LOGIN)
513 * Some systems have the bad habit of starting login shells with lots of open
514 * file descriptors. For instance, most systems that have picked up the
515 * pre-4.0 Sun YP code leave a file descriptor open each time you call one
516 * of the getpw* functions, and it's set to be open across execs. That
517 * means one for login, one for xterm, one for shelltool, etc.
519 if (login_shell
&& interactive_shell
)
521 for (i
= 3; i
< 20; i
++)
524 #endif /* CLOSE_FDS_AT_LOGIN */
526 /* From here on in, the shell must be a normal functioning shell.
527 Variables from the environment are expected to be set, etc. */
530 if (interactive_shell
)
532 char *term
= getenv ("TERM");
533 no_line_editing
|= term
&& (STREQ (term
, "emacs"));
536 top_level_arg_index
= arg_index
;
538 if (!quiet
&& do_version
)
539 show_shell_version ();
541 /* Give this shell a place to longjmp to before executing the
542 startup files. This allows users to press C-c to abort the
547 code
= setjmp (top_level
);
551 if (code
== EXITPROG
)
554 locally_skip_execution
++;
558 arg_index
= top_level_arg_index
;
560 /* Execute the start-up scripts. */
562 if (!interactive_shell
)
564 makunbound ("PS1", shell_variables
);
565 makunbound ("PS2", shell_variables
);
570 change_flag ('i', FLAG_ON
);
574 if (!locally_skip_execution
)
575 run_startup_files ();
577 #if defined (RESTRICTED_SHELL)
578 /* I turn on the restrictions afterwards because it is explictly
579 stated in the POSIX spec that PATH cannot be set in a restricted
580 shell, except in .profile. */
581 maybe_make_restricted (shell_name
);
582 #endif /* RESTRICTED_SHELL */
584 if (local_pending_command
)
586 /* Bind remaining args to $0 ... $n */
587 WORD_LIST
*args
= (WORD_LIST
*)NULL
;
588 while (arg_index
!= argc
)
589 args
= make_word_list (make_word (argv
[arg_index
++]), args
);
592 args
= REVERSE_LIST (args
, WORD_LIST
*);
593 /* Posix.2 4.56.3 says that the first argument after
594 sh -c command becomes $0, and the rest of the arguments
595 are bound to $1 ... $N. */
596 shell_name
= savestring (args
->word
->word
); /* XXX */
597 dollar_vars
[0] = savestring (args
->word
->word
);
598 remember_args (args
->next
, 1);
599 dispose_words (args
);
603 #if defined (ONESHOT)
604 run_one_command (local_pending_command
);
607 with_input_from_string (local_pending_command
, "-c");
608 goto read_and_execute
;
609 #endif /* !ONESHOT */
612 /* Do the things that should be done only for interactive shells. */
613 if (interactive_shell
)
615 /* Set up for checking for presence of mail. */
616 remember_mail_dates ();
619 #if defined (HISTORY)
620 /* Initialize the interactive history stuff. */
621 if (!shell_initialized
)
625 /* Initialize terminal state for interactive shells after the
626 .bash_profile and .bashrc are interpreted. */
630 /* Get possible input filename. */
631 if ((arg_index
!= argc
) && !read_from_stdin
)
636 free (dollar_vars
[0]);
637 dollar_vars
[0] = savestring (argv
[arg_index
]);
638 filename
= savestring (argv
[arg_index
]);
640 fd
= open (filename
, O_RDONLY
);
641 if ((fd
< 0) && (errno
== ENOENT
) && (absolute_program (filename
) == 0))
644 /* If it's not in the current directory, try looking through PATH
646 path_filename
= find_path_file (argv
[arg_index
]);
650 filename
= path_filename
;
651 fd
= open (filename
, O_RDONLY
);
658 file_error (filename
);
662 /* Only do this with file descriptors we can seek on. */
663 if (lseek (fd
, 0L, 1) != -1)
665 unsigned char sample
[80];
668 /* Check to see if the `file' in `bash file' is a binary file
669 according to the same tests done by execute_simple_command (),
670 and report an error and exit if it is. */
671 sample_len
= read (fd
, sample
, sizeof (sample
));
672 if (sample_len
> 0 && (check_binary_file (sample
, sample_len
)))
674 report_error ("%s: cannot execute binary file", filename
);
675 exit (EX_BINARY_FILE
);
677 /* Now rewind the file back to the beginning. */
681 #if defined (BUFFERED_INPUT)
682 default_buffered_input
= fd
;
683 if (default_buffered_input
== -1)
685 file_error (filename
);
688 SET_CLOSE_ON_EXEC (default_buffered_input
);
690 #else /* !BUFFERED_INPUT */
692 /* Open the script. But try to move the file descriptor to a randomly
693 large one, in the hopes that any descriptors used by the script will
694 not match with ours. */
698 nfds
= getdtablesize ();
703 script_fd
= dup2 (fd
, nfds
- 1);
711 default_input
= fdopen (fd
, "r");
715 file_error (filename
);
719 SET_CLOSE_ON_EXEC (fd
);
720 if (fileno (default_input
) != fd
)
721 SET_CLOSE_ON_EXEC (fileno (default_input
));
723 #endif /* !BUFFERED_INPUT */
725 if (!interactive_shell
|| (!isatty (fd
)))
727 #if defined (HISTORY)
728 # if defined (BANG_HISTORY)
729 history_expansion
= 0;
731 remember_on_history
= 0;
733 interactive
= interactive_shell
= 0;
735 #if defined (JOB_CONTROL)
737 #endif /* JOB_CONTROL */
741 /* I don't believe that this code is ever executed, even in
742 the presence of /dev/fd. */
745 fclose (default_input
);
748 else if (!interactive
)
749 /* In this mode, bash is reading a script from stdin, which is a
750 pipe or redirected file. */
751 #if defined (BUFFERED_INPUT)
752 default_buffered_input
= fileno (stdin
); /* == 0 */
754 setbuf (default_input
, (char *)NULL
);
755 #endif /* !BUFFERED_INPUT */
757 /* Bind remaining args to $1 ... $n */
759 WORD_LIST
*args
= (WORD_LIST
*)NULL
;
760 while (arg_index
!= argc
)
761 args
= make_word_list (make_word (argv
[arg_index
++]), args
);
762 args
= REVERSE_LIST (args
, WORD_LIST
*);
763 remember_args (args
, 1);
764 dispose_words (args
);
767 #if defined (BUFFERED_INPUT)
769 unset_nodelay_mode (default_buffered_input
);
771 unset_nodelay_mode (fileno (stdin
));
773 unset_nodelay_mode (fileno (stdin
));
774 #endif /* !BUFFERED_INPUT */
776 /* with_input_from_stdin really means `with_input_from_readline' */
777 if (interactive
&& !no_line_editing
)
778 with_input_from_stdin ();
780 #if defined (BUFFERED_INPUT)
783 with_input_from_buffered_stream (default_buffered_input
, dollar_vars
[0]);
785 with_input_from_stream (default_input
, dollar_vars
[0]);
787 #else /* !BUFFERED_INPUT */
788 with_input_from_stream (default_input
, dollar_vars
[0]);
789 #endif /* !BUFFERED_INPUT */
791 #if !defined (ONESHOT)
793 #endif /* !ONESHOT */
795 shell_initialized
= 1;
797 /* Read commands until exit condition. */
801 /* Do trap[0] if defined. */
802 if (signal_is_trapped (0))
803 last_command_exit_value
= run_exit_trap ();
805 #if defined (PROCESS_SUBSTITUTION)
807 #endif /* PROCESS_SUBSTITUTION */
809 #if defined (HISTORY)
810 if (interactive_shell
)
811 maybe_save_shell_history ();
814 #if defined (JOB_CONTROL)
815 /* If this shell is interactive, terminate all stopped jobs and
816 restore the original terminal process group. */
818 #endif /* JOB_CONTROL */
820 /* Always return the exit status of the last command to our parent. */
821 exit (last_command_exit_value
);
824 #if !defined (SYS_PROFILE)
825 # define SYS_PROFILE "/etc/profile"
826 #endif /* !SYS_PROFILE */
828 /* Source the bash startup files. If POSIXLY_CORRECT is non-zero, we obey
829 the Posix.2 startup file rules: $ENV is expanded, and if the file it
830 names exists, that file is sourced. The Posix.2 rules are in effect
831 for both interactive and non-interactive shells (section 4.56.5.3) */
835 if (!posixly_correct
)
839 /* We don't execute .bashrc for login shells. */
842 maybe_execute_file (SYS_PROFILE
, 1);
845 if (login_shell
&& !no_profile
)
848 maybe_execute_file ("~/.profile", 1);
851 if (maybe_execute_file ("~/.bash_profile", 1) == 0)
852 if (maybe_execute_file ("~/.bash_login", 1) == 0)
853 maybe_execute_file ("~/.profile", 1);
857 /* Execute ~/.bashrc for most shells. Never execute it if
858 ACT_LIKE_SH is set, or if NO_RC is set.
860 If the executable file "/usr/gnu/src/bash/foo" contains:
867 COMMAND EXECUTE BASHRC
868 --------------------------------
872 rsh machine ls YES (for rsh, which calls `bash -c')
873 rsh machine foo YES (for shell started by rsh) NO (for foo!)
878 if (!act_like_sh
&& !no_rc
&&
879 (interactive_shell
|| (isnetconn (fileno (stdin
)) &&
880 local_pending_command
)))
881 maybe_execute_file (bashrc_file
, 1);
884 /* Try a TMB suggestion. If running a script, then execute the
885 file mentioned in the ENV variable. */
886 if (!privileged_mode
&& sourced_env
++ == 0 && act_like_sh
== 0 &&
887 (posixly_correct
|| !interactive_shell
))
889 char *env_file
= (char *)NULL
;
891 if (!posixly_correct
)
892 env_file
= getenv ("BASH_ENV");
894 env_file
= getenv ("ENV");
896 if (env_file
&& *env_file
)
899 char *expanded_file_name
;
901 list
= expand_string_unsplit (env_file
, 1);
904 expanded_file_name
= string_list (list
);
905 dispose_words (list
);
907 if (expanded_file_name
&& *expanded_file_name
)
908 maybe_execute_file (expanded_file_name
, 1);
910 if (expanded_file_name
)
911 free (expanded_file_name
);
917 #if defined (RESTRICTED_SHELL)
918 /* Perhaps make this shell a `restricted' one, based on NAME.
919 If the basename of NAME is "rbash", then this shell is restricted.
920 In a restricted shell, PATH and SHELL are read-only and non-unsettable.
921 Do this also if `restricted' is already set to 1; maybe the shell was
923 maybe_make_restricted (name
)
928 temp
= base_pathname (shell_name
);
929 if (restricted
|| (STREQ (temp
, "rbash")))
931 set_var_read_only ("PATH");
932 non_unsettable ("PATH");
933 set_var_read_only ("SHELL");
934 non_unsettable ("SHELL");
938 #endif /* RESTRICTED_SHELL */
940 /* Try to execute the contents of FNAME. If FNAME doesn't exist,
941 that is not an error, but other kinds of errors are. A non-zero
942 FORCE_NONINTERACTIVE means to set the value of `interactive' to
943 0 so things like job control are disabled; the value is unchanged
944 otherwise. Returns -1 in the case of an error, 0 in the case that
945 the file was not found, and 1 if the file was found and executed. */
946 maybe_execute_file (fname
, force_noninteractive
)
948 int force_noninteractive
;
950 jmp_buf old_return_catch
;
951 int return_val
, fd
, tresult
, old_interactive
;
952 char *filename
, *string
;
953 struct stat file_info
;
955 filename
= tilde_expand (fname
);
956 fd
= open (filename
, O_RDONLY
);
962 file_error (filename
);
964 return ((errno
== ENOENT
) ? 0 : -1);
967 if (fstat (fd
, &file_info
) == -1)
968 goto file_error_and_exit
;
970 if (S_ISDIR (file_info
.st_mode
))
972 internal_error ("%s: cannot execute directories", filename
);
977 string
= (char *)xmalloc (1 + (int)file_info
.st_size
);
978 tresult
= read (fd
, string
, file_info
.st_size
);
986 if (tresult
!= file_info
.st_size
)
989 goto file_error_and_exit
;
991 string
[file_info
.st_size
] = '\0';
994 xbcopy ((char *)return_catch
, (char *)old_return_catch
, sizeof (jmp_buf));
996 if (force_noninteractive
)
998 old_interactive
= interactive
;
1002 return_val
= setjmp (return_catch
);
1004 /* If `return' was seen outside of a function, but in the script, then
1005 force parse_and_execute () to clean up. */
1007 parse_and_execute_cleanup ();
1009 tresult
= parse_and_execute (string
, filename
, -1);
1011 if (force_noninteractive
)
1012 interactive
= old_interactive
;
1014 return_catch_flag
--;
1015 xbcopy ((char *)old_return_catch
, (char *)return_catch
, sizeof (jmp_buf));
1022 #if defined (ONESHOT)
1023 /* Run one command, given as the argument to the -c option. Tell
1024 parse_and_execute not to fork for a simple command. */
1025 run_one_command (command
)
1030 code
= setjmp (top_level
);
1032 if (code
!= NOT_JUMPED
)
1034 #if defined (PROCESS_SUBSTITUTION)
1035 unlink_fifo_list ();
1036 #endif /* PROCESS_SUBSTITUTION */
1039 /* Some kind of throw to top_level has occured. */
1041 return last_command_exit_value
= 127;
1043 return last_command_exit_value
;
1045 return last_command_exit_value
= 1;
1047 programming_error ("Bad jump %d", code
);
1050 return (parse_and_execute (savestring (command
), "-c", -1));
1052 #endif /* ONESHOT */
1056 int our_indirection_level
;
1057 COMMAND
*current_command
= (COMMAND
*)NULL
;
1059 our_indirection_level
= ++indirection_level
;
1061 while (!EOF_Reached
)
1065 code
= setjmp (top_level
);
1067 #if defined (PROCESS_SUBSTITUTION)
1068 unlink_fifo_list ();
1069 #endif /* PROCESS_SUBSTITUTION */
1071 if (interactive_shell
&& signal_is_ignored (SIGINT
) == 0)
1072 set_signal_handler (SIGINT
, sigint_sighandler
);
1074 if (code
!= NOT_JUMPED
)
1076 indirection_level
= our_indirection_level
;
1080 /* Some kind of throw to top_level has occured. */
1083 current_command
= (COMMAND
*)NULL
;
1088 /* Obstack free command elements, etc. */
1089 if (current_command
)
1091 dispose_command (current_command
);
1092 current_command
= (COMMAND
*)NULL
;
1094 last_command_exit_value
= 1;
1098 programming_error ("Bad jump %d", code
);
1103 dispose_used_env_vars ();
1105 #if (defined (Ultrix) && defined (mips)) || !defined (HAVE_ALLOCA)
1106 /* Attempt to reclaim memory allocated with alloca (). */
1110 if (read_command () == 0)
1114 current_command
= global_command
;
1116 current_command_number
++;
1118 /* POSIX spec: "-n: The shell reads commands but does
1119 not execute them; this can be used to check for shell
1120 script syntax errors. The shell ignores the -n option
1121 for interactive shells. " */
1122 if (interactive_shell
|| !read_but_dont_execute
)
1125 execute_command (current_command
);
1129 if (current_command
)
1131 dispose_command (current_command
);
1132 current_command
= (COMMAND
*)NULL
;
1139 /* Parse error, maybe discard rest of stream if not interactive. */
1143 if (just_one_command
)
1146 indirection_level
--;
1149 /* Return a string denoting what our indirection level is. */
1150 static char indirection_string
[100];
1153 indirection_level_string ()
1158 indirection_string
[0] = '\0';
1159 ps4
= get_string_value ("PS4");
1161 if (ps4
== 0 || *ps4
== '\0')
1162 return (indirection_string
);
1164 ps4
= decode_prompt_string (ps4
);
1166 for (i
= 0; *ps4
&& i
< indirection_level
&& i
< 99; i
++)
1167 indirection_string
[i
] = *ps4
;
1169 for (j
= 1; *ps4
&& ps4
[j
] && i
< 99; i
++, j
++)
1170 indirection_string
[i
] = ps4
[j
];
1172 indirection_string
[i
] = '\0';
1174 return (indirection_string
);
1181 printf ("%ctimed out waiting for input: auto-logout\n", '\07');
1182 longjmp (top_level
, EXITPROG
);
1183 #if !defined (VOID_SIGHANDLER)
1185 #endif /* !VOID_SIGHANDLER */
1193 run_pending_traps ();
1195 /* Allow the execution of a random command just before the printing
1196 of each primary prompt. If the shell variable PROMPT_COMMAND
1197 is set then the value of it is the command to execute. */
1198 if (interactive
&& bash_input
.type
!= st_string
)
1200 char *command_to_execute
;
1202 command_to_execute
= get_string_value ("PROMPT_COMMAND");
1203 if (command_to_execute
)
1204 execute_prompt_command (command_to_execute
);
1207 current_command_line_count
= 0;
1211 gather_here_documents ();
1218 SHELL_VAR
*tmout_var
= (SHELL_VAR
*)NULL
;
1219 int tmout_len
= 0, result
;
1220 SigHandler
*old_alrm
= (SigHandler
*)NULL
;
1222 prompt_string_pointer
= &ps1_prompt
;
1223 global_command
= (COMMAND
*)NULL
;
1225 /* Only do timeouts if interactive. */
1228 tmout_var
= find_variable ("TMOUT");
1230 if (tmout_var
&& tmout_var
->value
)
1232 tmout_len
= atoi (tmout_var
->value
);
1235 old_alrm
= set_signal_handler (SIGALRM
, alrm_catcher
);
1243 current_command_line_count
= 0;
1244 result
= parse_command ();
1246 if (interactive
&& tmout_var
&& (tmout_len
> 0))
1249 set_signal_handler (SIGALRM
, old_alrm
);
1254 /* Cause STREAM to buffer lines as opposed to characters or blocks. */
1256 line_buffer_stream (stream
)
1259 /* If your machine doesn't have either of setlinebuf or setvbuf,
1260 you can just comment out the buffering commands, and the shell
1261 will still work. It will take more cycles, though. */
1262 #if defined (HAVE_SETLINEBUF)
1263 setlinebuf (stream
);
1265 # if defined (_IOLBF)
1266 # if defined (REVERSED_SETVBUF_ARGS)
1267 setvbuf (stream
, _IOLBF
, (char *)NULL
, BUFSIZ
);
1268 # else /* !REVERSED_SETVBUF_ARGS */
1269 setvbuf (stream
, (char *)NULL
, _IOLBF
, BUFSIZ
);
1270 # endif /* !REVERSED_SETVBUF_ARGS */
1271 # endif /* _IOLBF */
1272 #endif /* !HAVE_SETLINEBUF */
1275 /* Do whatever is necessary to initialize the shell.
1276 Put new initializations in here. */
1280 /* Line buffer output for stderr and stdout. */
1281 line_buffer_stream (stderr
);
1282 line_buffer_stream (stdout
);
1284 /* Sort the array of shell builtins so that the binary search in
1285 find_shell_builtin () works correctly. */
1286 initialize_shell_builtins ();
1288 /* Initialize the trap signal handlers before installing our own
1289 signal handlers. traps.c:restore_original_signals () is responsible
1290 for restoring the original default signal handlers. That function
1291 is called when we make a new child. */
1292 initialize_traps ();
1293 initialize_signals ();
1295 /* Initialize current_user.name and current_host_name. */
1297 struct passwd
*entry
= getpwuid (current_user
.uid
);
1300 if (gethostname (hostname
, 255) < 0)
1301 current_host_name
= "??host??";
1303 current_host_name
= savestring (hostname
);
1307 current_user
.user_name
= savestring (entry
->pw_name
);
1308 if (entry
->pw_shell
&& entry
->pw_shell
[0])
1309 current_user
.shell
= savestring (entry
->pw_shell
);
1311 current_user
.shell
= savestring ("/bin/sh");
1312 current_user
.home_dir
= savestring (entry
->pw_dir
);
1316 current_user
.user_name
= savestring ("I have no name!");
1317 current_user
.shell
= savestring ("/bin/sh");
1318 current_user
.home_dir
= savestring ("/");
1324 /* Initialize our interface to the tilde expander. */
1325 tilde_initialize ();
1327 /* Initialize internal and environment variables. */
1328 initialize_shell_variables (shell_environment
);
1330 /* Initialize filename hash tables. */
1331 initialize_filename_hashing ();
1333 /* Initialize the data structures for storing and running jobs. */
1336 /* Initialize input streams to null. */
1337 initialize_bash_input ();
1340 /* Function called by main () when it appears that the shell has already
1341 had some initialization performed. This is supposed to reset the world
1342 back to a pristine state, as if we had been exec'ed. */
1344 shell_reinitialize ()
1346 /* The default shell prompts. */
1347 primary_prompt
= PPROMPT
;
1348 secondary_prompt
= SPROMPT
;
1350 /* Things that get 1. */
1351 current_command_number
= 1;
1353 /* We have decided that the ~/.bashrc file should not be executed
1354 for the invocation of each shell script. If the variable $ENV
1355 (or $BASH_ENV) is set, its value is used as the name of a file
1357 no_rc
= no_profile
= 1;
1359 /* Things that get 0. */
1360 login_shell
= make_login_shell
= interactive
= executing
= 0;
1361 debugging
= do_version
= line_number
= last_command_exit_value
= 0;
1362 forced_interactive
= interactive_shell
= subshell_environment
= 0;
1364 #if defined (HISTORY)
1365 # if defined (BANG_HISTORY)
1366 history_expansion
= 0;
1368 remember_on_history
= 0;
1369 #endif /* HISTORY */
1371 #if defined (RESTRICTED_SHELL)
1373 #endif /* RESTRICTED_SHELL */
1375 /* Ensure that the default startup file is used. (Except that we don't
1376 execute this file for reinitialized shells). */
1377 bashrc_file
= "~/.bashrc";
1379 /* Delete all variables and functions. They will be reinitialized when
1380 the environment is parsed. */
1382 delete_all_variables (shell_variables
);
1383 delete_all_variables (shell_functions
);
1385 /* Pretend the PATH variable has changed. */
1390 initialize_signals ()
1392 initialize_terminating_signals ();
1393 initialize_job_signals ();
1394 #if defined (INITIALIZE_SIGLIST)
1395 initialize_siglist ();
1400 reinitialize_signals ()
1402 initialize_terminating_signals ();
1403 initialize_job_signals ();
1406 /* A structure describing a signal that terminates the shell if not
1407 caught. The orig_handler member is present so children can reset
1408 these signals back to their original handlers. */
1411 SigHandler
*orig_handler
;
1414 #define NULL_HANDLER (SigHandler *)SIG_DFL
1416 /* The list of signals that would terminate the shell if not caught.
1417 We catch them, but just so that we can write the history file,
1419 static struct termsig terminating_signals
[] = {
1421 SIGHUP
, NULL_HANDLER
,
1425 SIGINT
, NULL_HANDLER
,
1429 SIGILL
, NULL_HANDLER
,
1433 SIGTRAP
, NULL_HANDLER
,
1437 SIGIOT
, NULL_HANDLER
,
1441 SIGDANGER
, NULL_HANDLER
,
1445 SIGEMT
, NULL_HANDLER
,
1449 SIGFPE
, NULL_HANDLER
,
1453 SIGBUS
, NULL_HANDLER
,
1457 SIGSEGV
, NULL_HANDLER
,
1461 SIGSYS
, NULL_HANDLER
,
1465 SIGPIPE
, NULL_HANDLER
,
1469 SIGALRM
, NULL_HANDLER
,
1473 SIGTERM
, NULL_HANDLER
,
1477 SIGXCPU
, NULL_HANDLER
,
1481 SIGXFSZ
, NULL_HANDLER
,
1485 SIGVTALRM
, NULL_HANDLER
,
1489 SIGPROF
, NULL_HANDLER
,
1493 SIGLOST
, NULL_HANDLER
,
1497 SIGUSR1
, NULL_HANDLER
,
1501 SIGUSR2
, NULL_HANDLER
,
1505 #define TERMSIGS_LENGTH (sizeof (terminating_signals) / sizeof (struct termsig))
1507 #define XSIG(x) (terminating_signals[x].signum)
1508 #define XHANDLER(x) (terminating_signals[x].orig_handler)
1510 /* This function belongs here? */
1512 termination_unwind_protect (sig
)
1515 if (sig
== SIGINT
&& signal_is_trapped (SIGINT
))
1516 run_interrupt_trap ();
1518 #if defined (HISTORY)
1519 if (interactive_shell
)
1520 maybe_save_shell_history ();
1521 #endif /* HISTORY */
1523 #if defined (JOB_CONTROL)
1524 if (interactive
&& sig
== SIGHUP
)
1527 #endif /* JOB_CONTROL */
1529 #if defined (PROCESS_SUBSTITUTION)
1530 unlink_fifo_list ();
1531 #endif /* PROCESS_SUBSTITUTION */
1534 set_signal_handler (sig
, SIG_DFL
);
1535 kill (getpid (), sig
);
1537 #if !defined (VOID_SIGHANDLER)
1539 #endif /* VOID_SIGHANDLER */
1542 /* Initialize signals that will terminate the shell to do some
1543 unwind protection. */
1545 initialize_terminating_signals ()
1549 /* The following code is to avoid an expensive call to
1550 set_signal_handler () for each terminating_signals. Fortunately,
1551 this is possible in Posix. Unfortunately, we have to call signal ()
1552 on non-Posix systems for each signal in terminating_signals. */
1553 #if defined (_POSIX_VERSION)
1554 struct sigaction act
, oact
;
1556 act
.sa_handler
= termination_unwind_protect
;
1558 sigemptyset (&act
.sa_mask
);
1559 sigemptyset (&oact
.sa_mask
);
1560 for (i
= 0; i
< TERMSIGS_LENGTH
; i
++)
1561 sigaddset (&act
.sa_mask
, XSIG (i
));
1562 for (i
= 0; i
< TERMSIGS_LENGTH
; i
++)
1564 sigaction (XSIG (i
), &act
, &oact
);
1565 terminating_signals
[i
].orig_handler
= oact
.sa_handler
;
1566 /* Don't do anything with signals that are ignored at shell entry
1567 if the shell is not interactive. */
1568 if (!interactive_shell
&& oact
.sa_handler
== SIG_IGN
)
1570 sigaction (XSIG (i
), &oact
, &act
);
1571 set_signal_ignored (XSIG (i
));
1575 #else /* !_POSIX_VERSION */
1577 for (i
= 0; i
< TERMSIGS_LENGTH
; i
++)
1579 terminating_signals
[i
].orig_handler
=
1580 set_signal_handler (XSIG (i
), termination_unwind_protect
);
1581 /* Don't do anything with signals that are ignored at shell entry
1582 if the shell is not interactive. */
1583 if (!interactive_shell
&& terminating_signals
[i
].orig_handler
== SIG_IGN
)
1585 set_signal_handler (XSIG (i
), SIG_IGN
);
1586 set_signal_ignored (XSIG (i
));
1590 #endif /* !_POSIX_VERSION */
1592 #if defined (JOB_CONTROL) || defined (_POSIX_VERSION)
1593 /* All shells use the signal mask they inherit, and pass it along
1594 to child processes. Children will never block SIGCHLD, though. */
1595 sigemptyset (&top_level_mask
);
1596 sigprocmask (SIG_BLOCK
, (sigset_t
*)NULL
, &top_level_mask
);
1597 sigdelset (&top_level_mask
, SIGCHLD
);
1598 #endif /* JOB_CONTROL || _POSIX_VERSION */
1600 /* And, some signals that are specifically ignored by the shell. */
1601 set_signal_handler (SIGQUIT
, SIG_IGN
);
1605 set_signal_handler (SIGINT
, sigint_sighandler
);
1606 set_signal_handler (SIGTERM
, SIG_IGN
);
1611 reset_terminating_signals ()
1615 #if defined (_POSIX_VERSION)
1616 struct sigaction act
;
1619 sigemptyset (&act
.sa_mask
);
1620 for (i
= 0; i
< TERMSIGS_LENGTH
; i
++)
1622 /* Skip a signal if it's trapped or handled specially, because the
1623 trap code will restore the correct value. */
1624 if (signal_is_trapped (XSIG (i
)) || signal_is_special (XSIG (i
)))
1627 act
.sa_handler
= XHANDLER (i
);
1628 sigaction (XSIG (i
), &act
, (struct sigaction
*) NULL
);
1631 for (i
= 0; i
< TERMSIGS_LENGTH
; i
++)
1633 if (signal_is_trapped (XSIG (i
)) || signal_is_special (XSIG (i
)))
1636 set_signal_handler (XSIG (i
), XHANDLER (i
));
1643 /* What to do when we've been interrupted, and it is safe to handle it. */
1645 throw_to_top_level ()
1647 int print_newline
= 0;
1649 if (interrupt_state
)
1655 if (interrupt_state
)
1658 last_command_exit_value
|= 128;
1660 /* Run any traps set on SIGINT. */
1661 run_interrupt_trap ();
1663 /* Cleanup string parser environment. */
1664 while (parse_and_execute_level
)
1665 parse_and_execute_cleanup ();
1667 #if defined (JOB_CONTROL)
1668 give_terminal_to (shell_pgrp
);
1669 #endif /* JOB_CONTROL */
1671 #if defined (JOB_CONTROL) || defined (_POSIX_VERSION)
1672 sigprocmask (SIG_SETMASK
, &top_level_mask
, (sigset_t
*)NULL
);
1677 #if defined (READLINE)
1679 bashline_reinitialize ();
1680 #endif /* READLINE */
1682 #if defined (PROCESS_SUBSTITUTION)
1683 unlink_fifo_list ();
1684 #endif /* PROCESS_SUBSTITUTION */
1686 run_unwind_protects ();
1687 loop_level
= continuing
= breaking
= 0;
1688 return_catch_flag
= 0;
1690 if (interactive
&& print_newline
)
1693 fprintf (stderr
, "\n");
1697 /* An interrupted `wait' command in a script does not exit the script. */
1698 if (interactive
|| (interactive_shell
&& !shell_initialized
) ||
1699 (print_newline
&& signal_is_trapped (SIGINT
)))
1700 longjmp (top_level
, DISCARD
);
1702 longjmp (top_level
, EXITPROG
);
1705 /* When non-zero, we throw_to_top_level (). */
1706 int interrupt_immediately
= 0;
1708 /* What we really do when SIGINT occurs. */
1710 sigint_sighandler (sig
)
1713 #if defined (USG) && !defined (_POSIX_VERSION)
1714 set_signal_handler (sig
, sigint_sighandler
);
1717 /* interrupt_state needs to be set for the stack of interrupts to work
1718 right. Should it be set unconditionally? */
1719 if (!interrupt_state
)
1722 if (interrupt_immediately
)
1724 interrupt_immediately
= 0;
1725 throw_to_top_level ();
1727 #if !defined (VOID_SIGHANDLER)
1729 #endif /* VOID_SIGHANDLER */
1732 /* Give version information about this shell. */
1734 shell_version_string ()
1736 static char tt
[16] = { '\0' };
1739 sprintf (tt
, "%s.%d(%d)", dist_version
, patch_level
, build_version
);
1744 show_shell_version ()
1746 printf ("GNU %s, version %s\n", base_pathname (shell_name
),
1747 shell_version_string ());
1750 #if !defined (USG) && defined (ENOTSOCK)
1751 # if !defined (HAVE_SOCKETS)
1752 # define HAVE_SOCKETS
1756 #if defined (HAVE_SOCKETS)
1757 #include <sys/socket.h>
1760 /* Is FD a socket or network connection? */
1765 #if defined (USGr4) || defined (USGr4_2)
1766 /* Sockets on SVR4 and SVR4.2 are character special (streams) devices. */
1769 if (fstat (fd
, &sb
) < 0)
1771 return (S_ISCHR (sb
.st_mode
));
1772 #else /* !USGr4 && !USGr4_2 */
1773 # if defined (HAVE_SOCKETS)
1778 rv
= getpeername(0, &sa
, &l
);
1779 return ((rv
< 0 && errno
== ENOTSOCK
) ? 0 : 1);
1780 # else /* !HAVE_SOCKETS */
1781 # if defined (S_ISSOCK)
1784 if (fstat (fd
, &sb
) < 0)
1786 return (S_ISSOCK (sb
.st_mode
));
1787 # else /* !S_ISSOCK */
1789 # endif /* !S_ISSOCK */
1790 # endif /* !HAVE_SOCKETS */
1791 #endif /* !USGr4 && !USGr4_2 */