]> git.ipfire.org Git - thirdparty/bash.git/blobdiff - shell.c
Bash-5.2 patch 26: fix typo when specifying readline's custom color prefix
[thirdparty/bash.git] / shell.c
diff --git a/shell.c b/shell.c
index 91395d7fb7f2726b1a9c16f9589badeb506f18b2..ebd89651efc90f8fa09cf1774bb20de184a21b6f 100644 (file)
--- a/shell.c
+++ b/shell.c
@@ -1,23 +1,24 @@
 /* shell.c -- GNU's idea of the POSIX shell specification. */
 
-/* Copyright (C) 1987,1991 Free Software Foundation, Inc.
+/* Copyright (C) 1987-2021 Free Software Foundation, Inc.
 
    This file is part of GNU Bash, the Bourne Again SHell.
 
-   Bash is free software; you can redistribute it and/or modify it
-   under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2, or (at your option)
-   any later version.
+   Bash is free software: you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
 
-   Bash is distributed in the hope that it will be useful, but WITHOUT
-   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
-   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
-   License for more details.
+   Bash is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
-   along with Bash; see the file COPYING.  If not, write to the Free
-   Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA.
+   along with Bash.  If not, see <http://www.gnu.org/licenses/>.
+*/
 
+/*
   Birthdate:
   Sunday, January 10th, 1988.
   Initial author: Brian Fox
 #include "config.h"
 
 #include "bashtypes.h"
-#ifndef _MINIX
+#if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
 #  include <sys/file.h>
 #endif
 #include "posixstat.h"
+#include "posixtime.h"
 #include "bashansi.h"
 #include <stdio.h>
 #include <signal.h>
 #include <errno.h>
 #include "filecntl.h"
-#include <pwd.h>
+#if defined (HAVE_PWD_H)
+#  include <pwd.h>
+#endif
 
 #if defined (HAVE_UNISTD_H)
 #  include <unistd.h>
 #endif
 
+#include "bashintl.h"
+
+#define NEED_SH_SETLINEBUF_DECL                /* used in externs.h */
+
 #include "shell.h"
+#include "parser.h"
 #include "flags.h"
 #include "trap.h"
 #include "mailcheck.h"
 
 #if defined (JOB_CONTROL)
 #include "jobs.h"
+#else
+extern int running_in_background;
+extern int initialize_job_control PARAMS((int));
+extern int get_tty_state PARAMS((void));
 #endif /* JOB_CONTROL */
 
 #include "input.h"
 #include "execute_cmd.h"
 #include "findcmd.h"
 
+#if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
+#  include <malloc/shmalloc.h>
+#elif defined (MALLOC_DEBUG) && defined (USING_BASH_MALLOC)
+#  include <malloc/shmalloc.h>
+#endif
+
 #if defined (HISTORY)
 #  include "bashhist.h"
 #  include <readline/history.h>
 #endif
 
+#if defined (READLINE)
+#  include <readline/readline.h>
+#  include "bashline.h"
+#endif
+
 #include <tilde/tilde.h>
-#include <glob/fnmatch.h>
+#include <glob/strmatch.h>
 
 #if defined (__OPENNT)
 #  include <opennt/opennt.h>
@@ -81,27 +105,20 @@ extern int errno;
 extern char **environ; /* used if no third argument to main() */
 #endif
 
-extern char *dist_version, *release_status;
-extern int patch_level, build_version;
-extern int shell_level;
-extern int subshell_environment;
-extern int last_command_exit_value;
-extern int line_number;
-extern char *primary_prompt, *secondary_prompt;
-extern int expand_aliases;
-extern char *this_command_name;
-extern int array_needs_making;
+extern int gnu_error_format;
 
 /* Non-zero means that this shell has already been run; i.e. you should
    call shell_reinitialize () if you need to start afresh. */
 int shell_initialized = 0;
+int bash_argv_initialized = 0;
 
 COMMAND *global_command = (COMMAND *)NULL;
 
 /* Information about the current user. */
 struct user_info current_user =
 {
-  -1, -1, -1, -1, (char *)NULL, (char *)NULL, (char *)NULL
+  (uid_t)-1, (uid_t)-1, (gid_t)-1, (gid_t)-1,
+  (char *)NULL, (char *)NULL, (char *)NULL
 };
 
 /* The current host's name. */
@@ -111,7 +128,7 @@ char *current_host_name = (char *)NULL;
    Specifically:
    0 = not login shell.
    1 = login shell from getty (or equivalent fake out)
-  -1 = login shell from "--login" flag.
+  -1 = login shell from "--login" (or -l) flag.
   -2 = both from getty, and from flag.
  */
 int login_shell = 0;
@@ -128,13 +145,21 @@ int interactive_shell = 0;
    shell exits. */
 int hup_on_exit = 0;
 
+/* Non-zero means to list status of running and stopped jobs at shell exit */
+int check_jobs_at_exit = 0;
+
+/* Non-zero means to change to a directory name supplied as a command name */
+int autocd = 0;
+
 /* Tells what state the shell was in when it started:
        0 = non-interactive shell script
        1 = interactive
        2 = -c command
+       3 = wordexp evaluation
    This is a superset of the information provided by interactive_shell.
 */
 int startup_state = 0;
+int reading_shell_script = 0;
 
 /* Special debugging helper. */
 int debugging_login_shell = 0;
@@ -156,12 +181,20 @@ char *shell_name = (char *)NULL;
 
 /* time in seconds when the shell was started */
 time_t shell_start_time;
+struct timeval shellstart;
 
 /* Are we running in an emacs shell window? */
 int running_under_emacs;
 
+/* Do we have /dev/fd? */
+#ifdef HAVE_DEV_FD
+int have_devfd = HAVE_DEV_FD;
+#else
+int have_devfd = 0;
+#endif
+
 /* The name of the .(shell)rc file. */
-static char *bashrc_file = "~/.bashrc";
+static char *bashrc_file = DEFAULT_BASHRC;
 
 /* Non-zero means to act more like the Bourne shell on startup. */
 static int act_like_sh;
@@ -183,24 +216,44 @@ static int do_version;                    /* Display interesting version info. */
 static int make_login_shell;           /* Make this shell be a `-bash' shell. */
 static int want_initial_help;          /* --help option */
 
-int no_line_editing = 0;       /* Don't do fancy line editing. */
-int posixly_correct = 0;       /* Non-zero means posix.2 superset. */
+int debugging_mode = 0;                /* In debugging mode with --debugger */
+#if defined (READLINE)
+int no_line_editing = 0;       /* non-zero -> don't do fancy line editing. */
+#else
+int no_line_editing = 1;       /* can't have line editing without readline */
+#endif
+#if defined (TRANSLATABLE_STRINGS)
 int dump_translatable_strings; /* Dump strings in $"...", don't execute. */
 int dump_po_strings;           /* Dump strings in $"..." in po format */
+#endif
 int wordexp_only = 0;          /* Do word expansion only */
+int protected_mode = 0;                /* No command substitution with --wordexp */
+
+int pretty_print_mode = 0;     /* pretty-print a shell script */
+
+#if defined (STRICT_POSIX)
+int posixly_correct = 1;       /* Non-zero means posix.2 superset. */
+#else
+int posixly_correct = 0;       /* Non-zero means posix.2 superset. */
+#endif
 
 /* Some long-winded argument names.  These are obviously new. */
 #define Int 1
 #define Charp 2
-struct {
-  char *name;
+static const struct {
+  const char *name;
   int type;
   int *int_value;
   char **char_value;
 } long_args[] = {
   { "debug", Int, &debugging, (char **)0x0 },
+#if defined (DEBUGGER)
+  { "debugger", Int, &debugging_mode, (char **)0x0 },
+#endif
+#if defined (TRANSLATABLE_STRINGS)
   { "dump-po-strings", Int, &dump_po_strings, (char **)0x0 },
   { "dump-strings", Int, &dump_translatable_strings, (char **)0x0 },
+#endif
   { "help", Int, &want_initial_help, (char **)0x0 },
   { "init-file", Charp, (int *)0x0, &bashrc_file },
   { "login", Int, &make_login_shell, (char **)0x0 },
@@ -208,13 +261,19 @@ struct {
   { "noprofile", Int, &no_profile, (char **)0x0 },
   { "norc", Int, &no_rc, (char **)0x0 },
   { "posix", Int, &posixly_correct, (char **)0x0 },
+  { "pretty-print", Int, &pretty_print_mode, (char **)0x0 },
+#if defined (WORDEXP_OPTION)
+  { "protected", Int, &protected_mode, (char **)0x0 },
+#endif
   { "rcfile", Charp, (int *)0x0, &bashrc_file },
 #if defined (RESTRICTED_SHELL)
   { "restricted", Int, &restricted, (char **)0x0 },
 #endif
-  { "verbose", Int, &echo_input_at_read, (char **)0x0 },
+  { "verbose", Int, &verbose_flag, (char **)0x0 },
   { "version", Int, &do_version, (char **)0x0 },
+#if defined (WORDEXP_OPTION)
   { "wordexp", Int, &wordexp_only, (char **)0x0 },
+#endif
   { (char *)0x0, Int, (int *)0x0, (char **)0x0 }
 };
 
@@ -227,6 +286,8 @@ int subshell_argc;
 char **subshell_argv;
 char **subshell_envp;
 
+char *exec_argv0;
+
 #if defined (BUFFERED_INPUT)
 /* The file descriptor from which the shell is reading input. */
 int default_buffered_input = -1;
@@ -236,29 +297,51 @@ int default_buffered_input = -1;
 int read_from_stdin;           /* -s flag supplied */
 int want_pending_command;      /* -c flag supplied */
 
+/* This variable is not static so it can be bound to $BASH_EXECUTION_STRING */
+char *command_execution_string;        /* argument to -c option */
+char *shell_script_filename;   /* shell script */
+
+int malloc_trace_at_exit = 0;
+
 static int shell_reinitialized = 0;
-static char *local_pending_command;
 
 static FILE *default_input;
 
-static int parse_long_options ();
-static int parse_shell_options ();
-static void run_startup_files ();
-static int bind_args ();
-static int open_shell_script ();
-static void set_bash_input ();
-static int run_one_command ();
-static int run_wordexp ();
+static STRING_INT_ALIST *shopt_alist;
+static int shopt_ind = 0, shopt_len = 0;
 
-static int uidget ();
-static int isnetconn ();
+static int parse_long_options PARAMS((char **, int, int));
+static int parse_shell_options PARAMS((char **, int, int));
+static int bind_args PARAMS((char **, int, int, int));
+
+static void start_debugger PARAMS((void));
+
+static void add_shopt_to_alist PARAMS((char *, int));
+static void run_shopt_alist PARAMS((void));
+
+static void execute_env_file PARAMS((char *));
+static void run_startup_files PARAMS((void));
+static int open_shell_script PARAMS((char *));
+static void set_bash_input PARAMS((void));
+static int run_one_command PARAMS((char *));
+#if defined (WORDEXP_OPTION)
+static int run_wordexp PARAMS((char *));
+#endif
 
-static void init_interactive (), init_noninteractive ();
-static void set_shell_name ();
-static void shell_initialize ();
-static void shell_reinitialize ();
+static int uidget PARAMS((void));
 
-static void show_shell_usage ();
+static void set_option_defaults PARAMS((void));
+static void reset_option_defaults PARAMS((void));
+
+static void init_interactive PARAMS((void));
+static void init_noninteractive PARAMS((void));
+static void init_interactive_script PARAMS((void));
+
+static void set_shell_name PARAMS((char *));
+static void shell_initialize PARAMS((void));
+static void shell_reinitialize PARAMS((void));
+
+static void show_shell_usage PARAMS((FILE *, int));
 
 #ifdef __CYGWIN__
 static void
@@ -267,11 +350,11 @@ _cygwin32_check_tmp ()
   struct stat sb;
 
   if (stat ("/tmp", &sb) < 0)
-    internal_warning ("could not find /tmp, please create!");
+    internal_warning (_("could not find /tmp, please create!"));
   else
     {
       if (S_ISDIR (sb.st_mode) == 0)
-       internal_warning ("/tmp must be a valid directory name");
+       internal_warning (_("/tmp must be a valid directory name"));
     }
 }
 #endif /* __CYGWIN__ */
@@ -290,7 +373,10 @@ main (argc, argv, env)
 #endif /* !NO_MAIN_ENV_ARG */
 {
   register int i;
-  int code, saverst, old_errexit_flag;
+  int code, old_errexit_flag;
+#if defined (RESTRICTED_SHELL)
+  int saverst;
+#endif
   volatile int locally_skip_execution;
   volatile int arg_index, top_level_arg_index;
 #ifdef __OPENNT
@@ -299,11 +385,26 @@ main (argc, argv, env)
   env = environ;
 #endif /* __OPENNT */
 
+  USE_VAR(argc);
+  USE_VAR(argv);
+  USE_VAR(env);
+  USE_VAR(code);
+  USE_VAR(old_errexit_flag);
+#if defined (RESTRICTED_SHELL)
+  USE_VAR(saverst);
+#endif
+
   /* Catch early SIGINTs. */
-  code = setjmp (top_level);
+  code = setjmp_nosigs (top_level);
   if (code)
     exit (2);
 
+  xtrace_init ();
+
+#if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
+  malloc_set_register (1);     /* XXX - change to 1 for malloc debugging */
+#endif
+
   check_dev_tty ();
 
 #ifdef __CYGWIN__
@@ -311,7 +412,7 @@ main (argc, argv, env)
 #endif /* __CYGWIN__ */
 
   /* Wait forever if we are debugging a login shell. */
-  while (debugging_login_shell);
+  while (debugging_login_shell) sleep (3);
 
   set_default_locale ();
 
@@ -324,7 +425,7 @@ main (argc, argv, env)
   mcheck (programming_error, (void (*) ())0);
 #endif /* USE_GNU_MALLOC_LIBRARY */
 
-  if (setjmp (subshell_top_level))
+  if (setjmp_sigs (subshell_top_level))
     {
       argc = subshell_argc;
       argv = subshell_argv;
@@ -336,7 +437,9 @@ main (argc, argv, env)
 
   /* Initialize `local' variables for all `invocations' of main (). */
   arg_index = 1;
-  local_pending_command = (char *)NULL;
+  if (arg_index > argc)
+    arg_index = argc;
+  command_execution_string = shell_script_filename = (char *)NULL;
   want_pending_command = locally_skip_execution = read_from_stdin = 0;
   default_input = stdin;
 #if defined (BUFFERED_INPUT)
@@ -356,19 +459,21 @@ main (argc, argv, env)
        shell_name++;
 
       shell_reinitialize ();
-      if (setjmp (top_level))
+      if (setjmp_nosigs (top_level))
        exit (2);
     }
 
   shell_environment = env;
   set_shell_name (argv[0]);
-  shell_start_time = NOW;      /* NOW now defined in general.h */
+
+  gettimeofday (&shellstart, 0);
+  shell_start_time = shellstart.tv_sec;
 
   /* Parse argument flags from the input line. */
 
   /* Find full word arguments first. */
   arg_index = parse_long_options (argv, arg_index, argc);
-
+  
   if (want_initial_help)
     {
       show_shell_usage (stdout, 1);
@@ -381,22 +486,29 @@ main (argc, argv, env)
       exit (EXECUTION_SUCCESS);
     }
 
-  /* If user supplied the "--login" flag, then set and invert LOGIN_SHELL. */
+  echo_input_at_read = verbose_flag;   /* --verbose given */
+
+  /* All done with full word options; do standard shell option parsing.*/
+  this_command_name = shell_name;      /* for error reporting */
+  arg_index = parse_shell_options (argv, arg_index, argc);
+
+  /* If user supplied the "--login" (or -l) flag, then set and invert
+     LOGIN_SHELL. */
   if (make_login_shell)
     {
       login_shell++;
       login_shell = -login_shell;
     }
 
-  /* All done with full word options; do standard shell option parsing.*/
-  this_command_name = shell_name;      /* for error reporting */
-  arg_index = parse_shell_options (argv, arg_index, argc);
+  set_login_shell ("login_shell", login_shell != 0);
 
+#if defined (TRANSLATABLE_STRINGS)
   if (dump_po_strings)
     dump_translatable_strings = 1;
 
   if (dump_translatable_strings)
     read_but_dont_execute = 1;
+#endif
 
   if (running_setuid && privileged_mode == 0)
     disable_priv_mode ();
@@ -406,11 +518,11 @@ main (argc, argv, env)
      following args are $0...$n respectively. */
   if (want_pending_command)
     {
-      local_pending_command = argv[arg_index];
-      if (local_pending_command == 0)
+      command_execution_string = argv[arg_index];
+      if (command_execution_string == 0)
        {
-         report_error ("option `-c' requires an argument");
-         exit (EX_USAGE);
+         report_error (_("%s: option requires an argument"), "-c");
+         exit (EX_BADUSAGE);
        }
       arg_index++;
     }
@@ -422,59 +534,97 @@ main (argc, argv, env)
        no -c command
        no arguments remaining or the -s flag given
        standard input is a terminal
-       standard output is a terminal
+       standard error is a terminal
      Refer to Posix.2, the description of the `sh' utility. */
 
   if (forced_interactive ||            /* -i flag */
-      (!local_pending_command &&       /* No -c command and ... */
+      (!command_execution_string &&    /* No -c command and ... */
        wordexp_only == 0 &&            /* No --wordexp and ... */
        ((arg_index == argc) ||         /*   no remaining args or... */
        read_from_stdin) &&             /*   -s flag with args, and */
        isatty (fileno (stdin)) &&      /* Input is a terminal and */
-       isatty (fileno (stdout))))      /* output is a terminal. */
+       isatty (fileno (stderr))))      /* error output is a terminal. */
     init_interactive ();
   else
     init_noninteractive ();
 
-#define CLOSE_FDS_AT_LOGIN
-#if defined (CLOSE_FDS_AT_LOGIN)
   /*
    * Some systems have the bad habit of starting login shells with lots of open
    * file descriptors.  For instance, most systems that have picked up the
    * pre-4.0 Sun YP code leave a file descriptor open each time you call one
    * of the getpw* functions, and it's set to be open across execs.  That
-   * means one for login, one for xterm, one for shelltool, etc.
+   * means one for login, one for xterm, one for shelltool, etc.  There are
+   * also systems that open persistent FDs to other agents or files as part
+   * of process startup; these need to be set to be close-on-exec.
    */
   if (login_shell && interactive_shell)
     {
       for (i = 3; i < 20; i++)
-       close (i);
+       SET_CLOSE_ON_EXEC (i);
     }
-#endif /* CLOSE_FDS_AT_LOGIN */
 
-  /* If we're in a strict Posix.2 mode, turn on interactive comments and
-     other Posix.2 things. */
+  /* If we're in a strict Posix.2 mode, turn on interactive comments,
+     alias expansion in non-interactive shells, and other Posix.2 things. */
   if (posixly_correct)
     {
-      bind_variable ("POSIXLY_CORRECT", "y");
+      bind_variable ("POSIXLY_CORRECT", "y", 0);
       sv_strict_posix ("POSIXLY_CORRECT");
     }
 
+  /* Now we run the shopt_alist and process the options. */
+  if (shopt_alist)
+    run_shopt_alist ();
+
   /* From here on in, the shell must be a normal functioning shell.
      Variables from the environment are expected to be set, etc. */
   shell_initialize ();
 
+  set_default_lang ();
   set_default_locale_vars ();
 
+  /*
+   * M-x term -> TERM=eterm-color INSIDE_EMACS='251,term:0.96' (eterm)
+   * M-x shell -> TERM='dumb' INSIDE_EMACS='25.1,comint' (no line editing)
+   *
+   * Older versions of Emacs may set EMACS to 't' or to something like
+   * '22.1 (term:0.96)' instead of (or in addition to) setting INSIDE_EMACS.
+   * They may set TERM to 'eterm' instead of 'eterm-color'.  They may have
+   * a now-obsolete command that sets neither EMACS nor INSIDE_EMACS:
+   * M-x terminal -> TERM='emacs-em7955' (line editing)
+   */
   if (interactive_shell)
     {
-      char *term;
+      char *term, *emacs, *inside_emacs;
+      int emacs_term, in_emacs;
+
+      term = get_string_value ("TERM");
+      emacs = get_string_value ("EMACS");
+      inside_emacs = get_string_value ("INSIDE_EMACS");
+
+      if (inside_emacs)
+       {
+         emacs_term = strstr (inside_emacs, ",term:") != 0;
+         in_emacs = 1;
+       }
+      else if (emacs)
+       {
+         /* Infer whether we are in an older Emacs. */
+         emacs_term = strstr (emacs, " (term:") != 0;
+         in_emacs = emacs_term || STREQ (emacs, "t");
+       }
+      else
+       in_emacs = emacs_term = 0;
+
+      /* Not sure any emacs terminal emulator sets TERM=emacs any more */
+      no_line_editing |= STREQ (term, "emacs");
+      no_line_editing |= in_emacs && STREQ (term, "dumb");
+
+      /* running_under_emacs == 2 for `eterm' */
+      running_under_emacs = in_emacs || STREQN (term, "emacs", 5);
+      running_under_emacs += emacs_term && STREQN (term, "eterm", 5);
 
-      term = getenv ("TERM");
-      no_line_editing |= term && (STREQ (term, "emacs"));
-      term = getenv ("EMACS");
-      running_under_emacs = term ? ((fnmatch ("*term*", term, 0) == 0) ? 2 : 1)
-                                : 0;
+      if (running_under_emacs)
+       gnu_error_format = 1;
     }
 
   top_level_arg_index = arg_index;
@@ -483,10 +633,10 @@ main (argc, argv, env)
   /* Give this shell a place to longjmp to before executing the
      startup files.  This allows users to press C-c to abort the
      lengthy startup. */
-  code = setjmp (top_level);
+  code = setjmp_sigs (top_level);
   if (code)
     {
-      if (code == EXITPROG)
+      if (code == EXITPROG || code == ERREXIT || code == EXITBLTIN)
        exit_shell (last_command_exit_value);
       else
        {
@@ -507,10 +657,13 @@ main (argc, argv, env)
 
   if (interactive_shell == 0)
     {
-      makunbound ("PS1", shell_variables);
-      makunbound ("PS2", shell_variables);
+      unbind_variable ("PS1");
+      unbind_variable ("PS2");
       interactive = 0;
+#if 0
+      /* This has already been done by init_noninteractive */
       expand_aliases = posixly_correct;
+#endif
     }
   else
     {
@@ -530,20 +683,50 @@ main (argc, argv, env)
   restricted = 0;
 #endif
 
+  /* Set positional parameters before running startup files. top_level_arg_index
+     holds the index of the current argument before setting the positional
+     parameters, so any changes performed in the startup files won't affect
+     later option processing. */
+  if (wordexp_only)
+    ;                  /* nothing yet */
+  else if (command_execution_string)
+    arg_index = bind_args (argv, arg_index, argc, 0);  /* $0 ... $n */
+  else if (arg_index != argc && read_from_stdin == 0)
+    {
+      shell_script_filename = argv[arg_index++];
+      arg_index = bind_args (argv, arg_index, argc, 1);        /* $1 ... $n */
+    }
+  else
+    arg_index = bind_args (argv, arg_index, argc, 1);  /* $1 ... $n */
+
   /* The startup files are run with `set -e' temporarily disabled. */
   if (locally_skip_execution == 0 && running_setuid == 0)
     {
+      char *t;
+
       old_errexit_flag = exit_immediately_on_error;
       exit_immediately_on_error = 0;
 
+      /* Temporarily set $0 while running startup files, then restore it so
+        we get better error messages when trying to open script files. */
+      if (shell_script_filename)
+       {
+         t = dollar_vars[0];
+         dollar_vars[0] = exec_argv0 ? savestring (exec_argv0) : savestring (shell_script_filename);
+       }
       run_startup_files ();
+      if (shell_script_filename)
+       {
+         free (dollar_vars[0]);
+         dollar_vars[0] = t;
+       }
       exit_immediately_on_error += old_errexit_flag;
     }
 
   /* If we are invoked as `sh', turn on Posix mode. */
   if (act_like_sh)
     {
-      bind_variable ("POSIXLY_CORRECT", "y");
+      bind_variable ("POSIXLY_CORRECT", "y", 0);
       sv_strict_posix ("POSIXLY_CORRECT");
     }
 
@@ -556,57 +739,74 @@ main (argc, argv, env)
     maybe_make_restricted (shell_name);
 #endif /* RESTRICTED_SHELL */
 
+#if defined (WORDEXP_OPTION)
   if (wordexp_only)
     {
       startup_state = 3;
-      last_command_exit_value = run_wordexp (argv[arg_index]);
+      last_command_exit_value = run_wordexp (argv[top_level_arg_index]);
       exit_shell (last_command_exit_value);
     }
+#endif
 
-  if (local_pending_command)
+  cmd_init ();         /* initialize the command object caches */
+  uwp_init ();
+
+  if (command_execution_string)
     {
-      arg_index = bind_args (argv, arg_index, argc, 0);
       startup_state = 2;
+
+      if (debugging_mode)
+       start_debugger ();
+
 #if defined (ONESHOT)
-      run_one_command (local_pending_command);
+      executing = 1;
+      run_one_command (command_execution_string);
       exit_shell (last_command_exit_value);
 #else /* ONESHOT */
-      with_input_from_string (local_pending_command, "-c");
+      with_input_from_string (command_execution_string, "-c");
       goto read_and_execute;
 #endif /* !ONESHOT */
     }
 
   /* Get possible input filename and set up default_buffered_input or
      default_input as appropriate. */
-  if (arg_index != argc && read_from_stdin == 0)
-    {
-      open_shell_script (argv[arg_index]);
-      arg_index++;
-    }
+  if (shell_script_filename)
+    open_shell_script (shell_script_filename);
   else if (interactive == 0)
-    /* In this mode, bash is reading a script from stdin, which is a
-       pipe or redirected file. */
+    {
+      /* In this mode, bash is reading a script from stdin, which is a
+        pipe or redirected file. */
 #if defined (BUFFERED_INPUT)
-    default_buffered_input = fileno (stdin);   /* == 0 */
+      default_buffered_input = fileno (stdin); /* == 0 */
 #else
-    setbuf (default_input, (char *)NULL);
+      setbuf (default_input, (char *)NULL);
 #endif /* !BUFFERED_INPUT */
+      read_from_stdin = 1;
+    }
+  else if (top_level_arg_index == argc)                /* arg index before startup files */
+    /* "If there are no operands and the -c option is not specified, the -s
+       option shall be assumed." */
+    read_from_stdin = 1;
 
   set_bash_input ();
 
-  /* Bind remaining args to $1 ... $n */
-  arg_index = bind_args (argv, arg_index, argc, 1);
+  if (debugging_mode && locally_skip_execution == 0 && running_setuid == 0 && (reading_shell_script || interactive_shell == 0))
+    start_debugger ();
+
   /* Do the things that should be done only for interactive shells. */
   if (interactive_shell)
     {
       /* Set up for checking for presence of mail. */
-      remember_mail_dates ();
       reset_mail_timer ();
+      init_mail_dates ();
 
 #if defined (HISTORY)
       /* Initialize the interactive history stuff. */
       bash_initialize_history ();
-      if (shell_initialized == 0)
+      /* Don't load the history from the history file if we've already
+        saved some lines in this session (e.g., by putting `history -s xx'
+        into one of the startup files). */
+      if (shell_initialized == 0 && history_lines_this_session == 0)
        load_history ();
 #endif /* HISTORY */
 
@@ -621,6 +821,14 @@ main (argc, argv, env)
 
   shell_initialized = 1;
 
+  if (pretty_print_mode && interactive_shell)
+    {
+      internal_warning (_("pretty-printing mode ignored in interactive shells"));
+      pretty_print_mode = 0;
+    }
+  if (pretty_print_mode)
+    exit_shell (pretty_print_loop ());
+
   /* Read commands until exit condition. */
   reader_loop ();
   exit_shell (last_command_exit_value);
@@ -655,9 +863,8 @@ parse_long_options (argv, arg_start, arg_end)
                *long_args[i].int_value = 1;
              else if (argv[++arg_index] == 0)
                {
-                 report_error ("option `%s' requires an argument",
-                               long_args[i].name);
-                 exit (EX_USAGE);
+                 report_error (_("%s: option requires an argument"), long_args[i].name);
+                 exit (EX_BADUSAGE);
                }
              else
                *long_args[i].char_value = argv[arg_index];
@@ -669,9 +876,9 @@ parse_long_options (argv, arg_start, arg_end)
        {
          if (longarg)
            {
-             report_error ("%s: unrecognized option", argv[arg_index]);
+             report_error (_("%s: invalid option"), argv[arg_index]);
              show_shell_usage (stderr, 0);
-             exit (EX_USAGE);
+             exit (EX_BADUSAGE);
            }
          break;                /* No such argument.  Maybe flag arg. */
        }
@@ -716,6 +923,10 @@ parse_shell_options (argv, arg_start, arg_end)
              want_pending_command = 1;
              break;
 
+           case 'l':
+             make_login_shell = 1;
+             break;
+
            case 's':
              read_from_stdin = 1;
              break;
@@ -724,24 +935,43 @@ parse_shell_options (argv, arg_start, arg_end)
              o_option = argv[next_arg];
              if (o_option == 0)
                {
+                 set_option_defaults ();
                  list_minus_o_opts (-1, (on_or_off == '-') ? 0 : 1);
+                 reset_option_defaults ();
                  break;
                }
              if (set_minus_o_option (on_or_off, o_option) != EXECUTION_SUCCESS)
-               exit (EX_USAGE);
+               exit (EX_BADUSAGE);
+             next_arg++;
+             break;
+
+           case 'O':
+             /* Since some of these can be overridden by the normal
+                interactive/non-interactive shell initialization or
+                initializing posix mode, we save the options and process
+                them after initialization. */
+             o_option = argv[next_arg];
+             if (o_option == 0)
+               {
+                 shopt_listopt (o_option, (on_or_off == '-') ? 0 : 1);
+                 break;
+               }
+             add_shopt_to_alist (o_option, on_or_off);
              next_arg++;
              break;
 
            case 'D':
+#if defined (TRANSLATABLE_STRINGS)
              dump_translatable_strings = 1;
+#endif
              break;
 
            default:
              if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
                {
-                 report_error ("%c%c: unrecognized option", on_or_off, arg_character);
+                 report_error (_("%c%c: invalid option"), on_or_off, arg_character);
                  show_shell_usage (stderr, 0);
-                 exit (EX_USAGE);
+                 exit (EX_BADUSAGE);
                }
            }
        }
@@ -758,36 +988,53 @@ void
 exit_shell (s)
      int s;
 {
+  fflush (stdout);             /* XXX */
+  fflush (stderr);
+
+  /* Clean up the terminal if we are in a state where it's been modified. */
+#if defined (READLINE)
+  if (RL_ISSTATE (RL_STATE_TERMPREPPED) && rl_deprep_term_function)
+    (*rl_deprep_term_function) ();
+#endif
+  if (read_tty_modified ())
+    read_tty_cleanup ();
+
   /* Do trap[0] if defined.  Allow it to override the exit status
      passed to us. */
   if (signal_is_trapped (0))
     s = run_exit_trap ();
 
 #if defined (PROCESS_SUBSTITUTION)
-  unlink_fifo_list ();
+  unlink_all_fifos ();
 #endif /* PROCESS_SUBSTITUTION */
 
 #if defined (HISTORY)
-  if (interactive_shell)
+  if (remember_on_history)
     maybe_save_shell_history ();
 #endif /* HISTORY */
 
+#if defined (COPROCESS_SUPPORT)
+  coproc_flush ();
+#endif
+
 #if defined (JOB_CONTROL)
   /* If the user has run `shopt -s huponexit', hangup all jobs when we exit
      an interactive login shell.  ksh does this unconditionally. */
   if (interactive_shell && login_shell && hup_on_exit)
     hangup_all_jobs ();
 
-  /* If this shell is interactive, terminate all stopped jobs and
-     restore the original terminal process group.  Don't do this if we're
-     in a subshell and calling exit_shell after, for example, a failed
-     word expansion. */
+  /* If this shell is interactive, or job control is active, terminate all
+     stopped jobs and restore the original terminal process group.  Don't do
+     this if we're in a subshell and calling exit_shell after, for example,
+     a failed word expansion.  We want to do this even if the shell is not
+     interactive because we set the terminal's process group when job control
+     is enabled regardless of the interactive status. */
   if (subshell_environment == 0)
     end_job_control ();
 #endif /* JOB_CONTROL */
 
   /* Always return the exit status of the last command to our parent. */
-  exit (s);
+  sh_exit (s);
 }
 
 /* A wrapper for exit that (optionally) can do other things, like malloc
@@ -796,9 +1043,41 @@ void
 sh_exit (s)
      int s;
 {
+#if defined (MALLOC_DEBUG) && defined (USING_BASH_MALLOC)
+  if (malloc_trace_at_exit && (subshell_environment & (SUBSHELL_COMSUB|SUBSHELL_PROCSUB)) == 0)
+    trace_malloc_stats (get_name_for_error (), (char *)NULL);
+  /* mlocation_write_table (); */
+#endif
+
   exit (s);
 }
 
+/* Exit a subshell, which includes calling the exit trap.  We don't want to
+   do any more cleanup, since a subshell is created as an exact copy of its
+   parent. */
+void
+subshell_exit (s)
+     int s;
+{
+  fflush (stdout);
+  fflush (stderr);
+
+  /* Do trap[0] if defined.  Allow it to override the exit status
+     passed to us. */
+  last_command_exit_value = s;
+  if (signal_is_trapped (0))
+    s = run_exit_trap ();
+
+  sh_exit (s);
+}
+
+void
+set_exit_status (s)
+     int s;
+{
+  set_pipestatus_from_exit (last_command_exit_value = s);
+}
+
 /* Source the bash startup files.  If POSIXLY_CORRECT is non-zero, we obey
    the Posix.2 startup file rules:  $ENV is expanded, and if the file it
    names exists, that file is sourced.  The Posix.2 rules are in effect
@@ -831,20 +1110,13 @@ execute_env_file (env_file)
       char *env_file;
 {
   char *fn;
-  WORD_LIST *list;
 
   if (env_file && *env_file)
     {
-      list = expand_string_unsplit (env_file, Q_DOUBLE_QUOTES);
-      if (list)
-       {
-         fn = string_list (list);
-         dispose_words (list);
-
-         if (fn && *fn)
-           maybe_execute_file (fn, 1);
-         FREE (fn);
-       }
+      fn = expand_string_unsplit_to_string (env_file, Q_DOUBLE_QUOTES);
+      if (fn && *fn)
+       maybe_execute_file (fn, 1);
+      FREE (fn);
     }
 }
 
@@ -856,16 +1128,26 @@ run_startup_files ()
 #endif
   int sourced_login, run_by_ssh;
 
+#if 1  /* TAG:bash-5.3 andrew.gregory.8@gmail.com 2/21/2022 */
   /* get the rshd/sshd case out of the way first. */
   if (interactive_shell == 0 && no_rc == 0 && login_shell == 0 &&
-      act_like_sh == 0 && local_pending_command)
+      act_like_sh == 0 && command_execution_string)
     {
-      run_by_ssh = find_variable ("SSH_CLIENT") != (SHELL_VAR *)0;
-      run_by_ssh |= find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0;
+#ifdef SSH_SOURCE_BASHRC
+      run_by_ssh = (find_variable ("SSH_CLIENT") != (SHELL_VAR *)0) ||
+                  (find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0);
+#else
+      run_by_ssh = 0;
+#endif
+#endif
 
       /* If we were run by sshd or we think we were run by rshd, execute
         ~/.bashrc if we are a top-level shell. */
+#if 1  /* TAG:bash-5.3 */
       if ((run_by_ssh || isnetconn (fileno (stdin))) && shell_level < 2)
+#else
+      if (isnetconn (fileno (stdin) && shell_level < 2)
+#endif
        {
 #ifdef SYS_BASHRC
 #  if defined (__OPENNT)
@@ -886,8 +1168,8 @@ run_startup_files ()
 
   sourced_login = 0;
 
-  /* A shell begun with the --login flag that is not in posix mode runs
-     the login shell startup files, no matter whether or not it is
+  /* A shell begun with the --login (or -l) flag that is not in posix mode
+     runs the login shell startup files, no matter whether or not it is
      interactive.  If NON_INTERACTIVE_LOGIN_SHELLS is defined, run the
      startup files if argv[0][0] == '-' as well. */
 #if defined (NON_INTERACTIVE_LOGIN_SHELLS)
@@ -990,6 +1272,8 @@ shell_is_restricted (name)
   if (restricted)
     return 1;
   temp = base_pathname (name);
+  if (*temp == '-')
+    temp++;
   return (STREQ (temp, RESTRICTED_SHELL_NAME));
 }
 
@@ -1006,13 +1290,20 @@ maybe_make_restricted (name)
 {
   char *temp;
 
-  temp = base_pathname (shell_name);
+  temp = base_pathname (name);
+  if (*temp == '-')
+    temp++;
   if (restricted || (STREQ (temp, RESTRICTED_SHELL_NAME)))
     {
+#if defined (RBASH_STATIC_PATH_VALUE)
+      bind_variable ("PATH", RBASH_STATIC_PATH_VALUE, 0);
+      stupidly_hack_special_variables ("PATH");                /* clear hash table */
+#endif
       set_var_read_only ("PATH");
       set_var_read_only ("SHELL");
       set_var_read_only ("ENV");
       set_var_read_only ("BASH_ENV");
+      set_var_read_only ("HISTFILE");
       restricted = 1;
     }
   return (restricted);
@@ -1047,30 +1338,52 @@ uidget ()
 void
 disable_priv_mode ()
 {
-  setuid (current_user.uid);
-  setgid (current_user.gid);
+  int e;
+
+#if HAVE_SETRESUID
+  if (setresuid (current_user.uid, current_user.uid, current_user.uid) < 0)
+#else
+  if (setuid (current_user.uid) < 0)
+#endif
+    {
+      e = errno;
+      sys_error (_("cannot set uid to %d: effective uid %d"), current_user.uid, current_user.euid);
+#if defined (EXIT_ON_SETUID_FAILURE)
+      if (e == EAGAIN)
+       exit (e);
+#endif
+    }
+#if HAVE_SETRESGID
+  if (setresgid (current_user.gid, current_user.gid, current_user.gid) < 0)
+#else
+  if (setgid (current_user.gid) < 0)
+#endif
+    sys_error (_("cannot set gid to %d: effective gid %d"), current_user.gid, current_user.egid);
+
   current_user.euid = current_user.uid;
   current_user.egid = current_user.gid;
 }
 
+#if defined (WORDEXP_OPTION)
 static int
 run_wordexp (words)
      char *words;
 {
   int code, nw, nb;
-  WORD_DESC *w;
-  WORD_LIST *wl, *result;
+  WORD_LIST *wl, *tl, *result;
 
-  code = setjmp (top_level);
+  code = setjmp_nosigs (top_level);
 
   if (code != NOT_JUMPED)
     {
       switch (code)
        {
-         /* Some kind of throw to top_level has occured. */
+         /* Some kind of throw to top_level has occurred. */
        case FORCE_EOF:
          return last_command_exit_value = 127;
+       case ERREXIT:
        case EXITPROG:
+       case EXITBLTIN:
          return last_command_exit_value;
        case DISCARD:
          return last_command_exit_value = 1;
@@ -1093,6 +1406,9 @@ run_wordexp (words)
       if (global_command->type != cm_simple)
        return (126);
       wl = global_command->value.Simple->words;
+      if (protected_mode)
+       for (tl = wl; tl; tl = tl->next)
+         tl->word->flags |= W_NOCOMSUB|W_NOPROCSUB;
       result = wl ? expand_words_no_vars (wl) : (WORD_LIST *)0;
     }
   else
@@ -1121,6 +1437,7 @@ run_wordexp (words)
 
   return (0);
 }
+#endif
 
 #if defined (ONESHOT)
 /* Run one command, given as the argument to the -c option.  Tell
@@ -1131,7 +1448,7 @@ run_one_command (command)
 {
   int code;
 
-  code = setjmp (top_level);
+  code = setjmp_nosigs (top_level);
 
   if (code != NOT_JUMPED)
     {
@@ -1140,10 +1457,12 @@ run_one_command (command)
 #endif /* PROCESS_SUBSTITUTION */
       switch (code)
        {
-         /* Some kind of throw to top_level has occured. */
+         /* Some kind of throw to top_level has occurred. */
        case FORCE_EOF:
          return last_command_exit_value = 127;
+       case ERREXIT:
        case EXITPROG:
+       case EXITBLTIN:
          return last_command_exit_value;
        case DISCARD:
          return last_command_exit_value = 1;
@@ -1151,7 +1470,7 @@ run_one_command (command)
          command_error ("run_one_command", CMDERR_BADJUMP, code, 0);
        }
     }
-   return (parse_and_execute (savestring (command), "-c", SEVAL_NOHIST));
+   return (parse_and_execute (savestring (command), "-c", SEVAL_NOHIST|SEVAL_RESETLINE));
 }
 #endif /* ONESHOT */
 
@@ -1161,13 +1480,21 @@ bind_args (argv, arg_start, arg_end, start_index)
      int arg_start, arg_end, start_index;
 {
   register int i;
-  WORD_LIST *args;
+  WORD_LIST *args, *tl;
+
+  for (i = arg_start, args = tl = (WORD_LIST *)NULL; i < arg_end; i++)
+    {
+      if (args == 0)
+       args = tl = make_word_list (make_word (argv[i]), args);
+      else
+       {
+         tl->next = make_word_list (make_word (argv[i]), (WORD_LIST *)NULL);
+         tl = tl->next;
+       }
+    }
 
-  for (i = arg_start, args = (WORD_LIST *)NULL; i != arg_end; i++)
-    args = make_word_list (make_word (argv[i]), args);
   if (args)
     {
-      args = REVERSE_LIST (args, WORD_LIST *);
       if (start_index == 0)    /* bind to $0...$n for sh -c command */
        {
          /* Posix.2 4.56.3 says that the first argument after sh -c command
@@ -1176,9 +1503,24 @@ bind_args (argv, arg_start, arg_end, start_index)
          FREE (dollar_vars[0]);
          dollar_vars[0] = savestring (args->word->word);
          remember_args (args->next, 1);
+         if (debugging_mode)
+           {
+             push_args (args->next);   /* BASH_ARGV and BASH_ARGC */
+             bash_argv_initialized = 1;
+           }
        }
       else                     /* bind to $1...$n for shell script */
-       remember_args (args, 1);
+        {
+         remember_args (args, 1);
+         /* We do this unconditionally so something like -O extdebug doesn't
+            do it first.  We're setting the definitive positional params
+            here. */
+         if (debugging_mode)
+           {
+             push_args (args);         /* BASH_ARGV and BASH_ARGC */
+             bash_argv_initialized = 1;
+           }
+        }
 
       dispose_words (args);
     }
@@ -1190,6 +1532,32 @@ void
 unbind_args ()
 {
   remember_args ((WORD_LIST *)NULL, 1);
+  pop_args ();                         /* Reset BASH_ARGV and BASH_ARGC */
+}
+
+static void
+start_debugger ()
+{
+#if defined (DEBUGGER) && defined (DEBUGGER_START_FILE)
+  int old_errexit;
+  int r;
+
+  old_errexit = exit_immediately_on_error;
+  exit_immediately_on_error = 0;
+
+  r = force_execute_file (DEBUGGER_START_FILE, 1);
+  if (r < 0)
+    {
+      internal_warning (_("cannot start debugger; debugging mode disabled"));
+      debugging_mode = 0;
+    }
+  error_trace_mode = function_trace_mode = debugging_mode;
+
+  set_shellopts ();
+  set_bashopts ();
+
+  exit_immediately_on_error += old_errexit;
+#endif
 }
 
 static int
@@ -1197,13 +1565,15 @@ open_shell_script (script_name)
      char *script_name;
 {
   int fd, e, fd_is_tty;
-  char *filename, *path_filename;
-  unsigned char sample[80];
+  char *filename, *path_filename, *t;
+  char sample[80];
   int sample_len;
   struct stat sb;
+#if defined (ARRAY_VARS)
+  SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
+  ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
+#endif
 
-  free (dollar_vars[0]);
-  dollar_vars[0] = savestring (script_name);
   filename = savestring (script_name);
 
   fd = open (filename, O_RDONLY);
@@ -1227,8 +1597,48 @@ open_shell_script (script_name)
     {
       e = errno;
       file_error (filename);
-      exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
+#if defined (JOB_CONTROL)
+      end_job_control ();      /* just in case we were run as bash -i script */
+#endif
+      sh_exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
+    }
+
+  free (dollar_vars[0]);
+  dollar_vars[0] = exec_argv0 ? savestring (exec_argv0) : savestring (script_name);
+  if (exec_argv0)
+    {
+      free (exec_argv0);
+      exec_argv0 = (char *)NULL;
+    }
+
+  if (file_isdir (filename))
+    {
+#if defined (EISDIR)
+      errno = EISDIR;
+#else
+      errno = EINVAL;
+#endif
+      file_error (filename);
+#if defined (JOB_CONTROL)
+      end_job_control ();      /* just in case we were run as bash -i script */
+#endif
+      sh_exit (EX_NOINPUT);
+    }
+
+#if defined (ARRAY_VARS)
+  GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
+  GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
+  GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
+
+  array_push (bash_source_a, filename);
+  if (bash_lineno_a)
+    {
+      t = itos (executing_line_number ());
+      array_push (bash_lineno_a, t);
+      free (t);
     }
+  array_push (funcname_a, "main");
+#endif
 
 #ifdef HAVE_DEV_FD
   fd_is_tty = isatty (fd);
@@ -1247,17 +1657,30 @@ open_shell_script (script_name)
        {
          e = errno;
          if ((fstat (fd, &sb) == 0) && S_ISDIR (sb.st_mode))
-           internal_error ("%s: is a directory", filename);
+           {
+#if defined (EISDIR)
+             errno = EISDIR;
+             file_error (filename);
+#else        
+             internal_error (_("%s: Is a directory"), filename);
+#endif
+           }
          else
            {
              errno = e;
              file_error (filename);
            }
+#if defined (JOB_CONTROL)
+         end_job_control ();   /* just in case we were run as bash -i script */
+#endif
          exit (EX_NOEXEC);
        }
       else if (sample_len > 0 && (check_binary_file (sample, sample_len)))
        {
-         internal_error ("%s: cannot execute binary file", filename);
+         internal_error (_("%s: cannot execute binary file"), filename);
+#if defined (JOB_CONTROL)
+         end_job_control ();   /* just in case we were run as bash -i script */
+#endif
          exit (EX_BINARY_FILE);
        }
       /* Now rewind the file back to the beginning. */
@@ -1267,11 +1690,7 @@ open_shell_script (script_name)
   /* Open the script.  But try to move the file descriptor to a randomly
      large one, in the hopes that any descriptors used by the script will
      not match with ours. */
-  fd = move_to_high_fd (fd, 0, -1);
-
-#if defined (__CYGWIN__) && defined (O_TEXT)
-  setmode (fd, O_TEXT);
-#endif
+  fd = move_to_high_fd (fd, 1, -1);
 
 #if defined (BUFFERED_INPUT)
   default_buffered_input = fd;
@@ -1304,8 +1723,15 @@ open_shell_script (script_name)
       default_input = stdin;
 #endif
     }
+  else if (forced_interactive && fd_is_tty == 0)
+    /* But if a script is called with something like `bash -i scriptname',
+       we need to do a non-interactive setup here, since we didn't do it
+       before. */
+    init_interactive_script ();
 
   free (filename);
+
+  reading_shell_script = 1;
   return (fd);
 }
 
@@ -1325,17 +1751,12 @@ set_bash_input ()
   /* with_input_from_stdin really means `with_input_from_readline' */
   if (interactive && no_line_editing == 0)
     with_input_from_stdin ();
-  else
 #if defined (BUFFERED_INPUT)
-    {
-      if (interactive == 0)
-       with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
-      else
-       with_input_from_stream (default_input, dollar_vars[0]);
-    }
-#else /* !BUFFERED_INPUT */
+  else if (interactive == 0)
+    with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
+#endif /* BUFFERED_INPUT */
+  else
     with_input_from_stream (default_input, dollar_vars[0]);
-#endif /* !BUFFERED_INPUT */
 }
 
 /* Close the current shell script input source and forget about it.  This is
@@ -1352,6 +1773,7 @@ unset_bash_input (check_zero)
     {
       close_buffered_fd (default_buffered_input);
       default_buffered_input = bash_input.location.buffered_fd = -1;
+      bash_input.type = st_none;               /* XXX */
     }
 #else /* !BUFFERED_INPUT */
   if (default_input)
@@ -1373,24 +1795,24 @@ set_shell_name (argv0)
 {
   /* Here's a hack.  If the name of this shell is "sh", then don't do
      any startup files; just try to be more like /bin/sh. */
-  shell_name = base_pathname (argv0);
-  if (*shell_name == '-')
-    shell_name++;
+  shell_name = argv0 ? base_pathname (argv0) : PROGRAM;
+
+  if (argv0 && *argv0 == '-')
+    {
+      if (*shell_name == '-')
+       shell_name++;
+      login_shell = 1;
+    }
+
   if (shell_name[0] == 's' && shell_name[1] == 'h' && shell_name[2] == '\0')
     act_like_sh++;
   if (shell_name[0] == 's' && shell_name[1] == 'u' && shell_name[2] == '\0')
     su_shell++;
 
-  shell_name = argv0;
+  shell_name = argv0 ? argv0 : PROGRAM;
   FREE (dollar_vars[0]);
   dollar_vars[0] = savestring (shell_name);
 
-  if (*shell_name == '-')
-    {
-      shell_name++;
-      login_shell++;
-    }
-
   /* A program may start an interactive shell with
          "execl ("/bin/bash", "-", NULL)".
      If so, default the name of this shell to our name. */
@@ -1398,27 +1820,74 @@ set_shell_name (argv0)
     shell_name = PROGRAM;
 }
 
+/* Some options are initialized to -1 so we have a way to determine whether
+   they were set on the command line. This is an issue when listing the option
+   values at invocation (`bash -o'), so we set the defaults here and reset
+   them after the call to list_minus_o_options (). */
+/* XXX - could also do this for histexp_flag, jobs_m_flag */
+static void
+set_option_defaults ()
+{
+#if defined (HISTORY)
+  enable_history_list = 0;
+#endif
+}
+
+static void
+reset_option_defaults ()
+{
+#if defined (HISTORY)
+  enable_history_list = -1;
+#endif
+}
+
 static void
 init_interactive ()
 {
+  expand_aliases = expaliases_flag = 1;
   interactive_shell = startup_state = interactive = 1;
-  expand_aliases = 1;
+#if defined (HISTORY)
+  if (enable_history_list == -1)
+    enable_history_list = 1;                           /* set default  */
+  remember_on_history = enable_history_list;
+#  if defined (BANG_HISTORY)
+  histexp_flag = history_expansion;                    /* XXX */
+#  endif
+#endif
 }
 
 static void
 init_noninteractive ()
 {
 #if defined (HISTORY)
+  if (enable_history_list == -1)                       /* set default */
+    enable_history_list = 0;
   bash_history_reinit (0);
 #endif /* HISTORY */
   interactive_shell = startup_state = interactive = 0;
-  expand_aliases = 0;
+  expand_aliases = expaliases_flag = posixly_correct;  /* XXX - was 0 not posixly_correct */
   no_line_editing = 1;
 #if defined (JOB_CONTROL)
-  set_job_control (0);
+  /* Even if the shell is not interactive, enable job control if the -i or
+     -m option is supplied at startup. */
+  set_job_control (forced_interactive||jobs_m_flag);
 #endif /* JOB_CONTROL */
 }
 
+static void
+init_interactive_script ()
+{
+#if defined (HISTORY)
+  if (enable_history_list == -1)
+    enable_history_list = 1;
+#endif
+  init_noninteractive ();
+  expand_aliases = expaliases_flag = interactive_shell = startup_state = 1;
+#if defined (HISTORY)
+  remember_on_history = enable_history_list;   /* XXX */
+#endif
+}
+
 void
 get_current_user_info ()
 {
@@ -1427,7 +1896,11 @@ get_current_user_info ()
   /* Don't fetch this more than once. */
   if (current_user.user_name == 0)
     {
+#if defined (__TANDEM)
+      entry = getpwnam (getlogin ());
+#else
       entry = getpwuid (current_user.uid);
+#endif
       if (entry)
        {
          current_user.user_name = savestring (entry->pw_name);
@@ -1438,11 +1911,14 @@ get_current_user_info ()
        }
       else
        {
-         current_user.user_name = savestring ("I have no name!");
+         current_user.user_name = _("I have no name!");
+         current_user.user_name = savestring (current_user.user_name);
          current_user.shell = savestring ("/bin/sh");
          current_user.home_dir = savestring ("/");
        }
+#if defined (HAVE_GETPWENT)
       endpwent ();
+#endif
     }
 }
 
@@ -1452,6 +1928,7 @@ static void
 shell_initialize ()
 {
   char hostname[256];
+  int should_be_restricted;
 
   /* Line buffer output for stderr and stdout. */
   if (shell_initialized == 0)
@@ -1469,7 +1946,7 @@ shell_initialize ()
      for restoring the original default signal handlers.  That function
      is called when we make a new child. */
   initialize_traps ();
-  initialize_signals ();
+  initialize_signals (0);
 
   /* It's highly unlikely that this will change. */
   if (current_host_name == 0)
@@ -1490,33 +1967,37 @@ shell_initialize ()
   /* Initialize our interface to the tilde expander. */
   tilde_initialize ();
 
+#if defined (RESTRICTED_SHELL)
+  should_be_restricted = shell_is_restricted (shell_name);
+#endif
+
   /* Initialize internal and environment variables.  Don't import shell
      functions from the environment if we are running in privileged or
      restricted mode or if the shell is running setuid. */
 #if defined (RESTRICTED_SHELL)
-  initialize_shell_variables (shell_environment, privileged_mode||restricted||running_setuid);
+  initialize_shell_variables (shell_environment, privileged_mode||restricted||should_be_restricted||running_setuid);
 #else
   initialize_shell_variables (shell_environment, privileged_mode||running_setuid);
 #endif
 
-#if 0
-  /* Initialize filename hash tables. */
-  initialize_filename_hashing ();
-#endif
-
   /* Initialize the data structures for storing and running jobs. */
-  initialize_job_control (0);
+  initialize_job_control (jobs_m_flag);
 
   /* Initialize input streams to null. */
   initialize_bash_input ();
 
+  initialize_flags ();
+
   /* Initialize the shell options.  Don't import the shell options
-     from the environment variable $SHELLOPTS if we are running in
-     privileged or restricted mode or if the shell is running setuid. */
+     from the environment variables $SHELLOPTS or $BASHOPTS if we are
+     running in privileged or restricted mode or if the shell is running
+     setuid. */
 #if defined (RESTRICTED_SHELL)
-  initialize_shell_options (privileged_mode||restricted||running_setuid);
+  initialize_shell_options (privileged_mode||restricted||should_be_restricted||running_setuid);
+  initialize_bashopts (privileged_mode||restricted||should_be_restricted||running_setuid);
 #else
   initialize_shell_options (privileged_mode||running_setuid);
+  initialize_bashopts (privileged_mode||running_setuid);
 #endif
 }
 
@@ -1542,11 +2023,15 @@ shell_reinitialize ()
   /* Things that get 0. */
   login_shell = make_login_shell = interactive = executing = 0;
   debugging = do_version = line_number = last_command_exit_value = 0;
-  forced_interactive = interactive_shell = subshell_environment = 0;
-  expand_aliases = 0;
+  forced_interactive = interactive_shell = 0;
+  subshell_environment = running_in_background = 0;
+  expand_aliases = expaliases_flag = 0;
+  bash_argv_initialized = 0;
+
+  /* XXX - should we set jobs_m_flag to 0 here? */
 
 #if defined (HISTORY)
-  bash_history_reinit (0);
+  bash_history_reinit (enable_history_list = 0);
 #endif /* HISTORY */
 
 #if defined (RESTRICTED_SHELL)
@@ -1555,13 +2040,19 @@ shell_reinitialize ()
 
   /* Ensure that the default startup file is used.  (Except that we don't
      execute this file for reinitialized shells). */
-  bashrc_file = "~/.bashrc";
+  bashrc_file = DEFAULT_BASHRC;
 
   /* Delete all variables and functions.  They will be reinitialized when
      the environment is parsed. */
-  delete_all_variables (shell_variables);
+  delete_all_contexts (shell_variables);
   delete_all_variables (shell_functions);
 
+  reinit_special_variables ();
+
+#if defined (READLINE)
+  bashline_reinitialize ();
+#endif
+
   shell_reinitialized = 1;
 }
 
@@ -1574,19 +2065,23 @@ show_shell_usage (fp, extra)
   char *set_opts, *s, *t;
 
   if (extra)
-    fprintf (fp, "GNU bash, version %s-(%s)\n", shell_version_string (), MACHTYPE);
-  fprintf (fp, "Usage:\t%s [GNU long option] [option] ...\n\t%s [GNU long option] [option] script-file ...\n",
+    fprintf (fp, _("GNU bash, version %s-(%s)\n"), shell_version_string (), MACHTYPE);
+  fprintf (fp, _("Usage:\t%s [GNU long option] [option] ...\n\t%s [GNU long option] [option] script-file ...\n"),
             shell_name, shell_name);
-  fputs ("GNU long options:\n", fp);
+  fputs (_("GNU long options:\n"), fp);
   for (i = 0; long_args[i].name; i++)
     fprintf (fp, "\t--%s\n", long_args[i].name);
 
-  fputs ("Shell options:\n", fp);
-  fputs ("\t-irsD or -c command\t\t(invocation only)\n", fp);
+  fputs (_("Shell options:\n"), fp);
+  fputs (_("\t-ilrsD or -c command or -O shopt_option\t\t(invocation only)\n"), fp);
 
   for (i = 0, set_opts = 0; shell_builtins[i].name; i++)
     if (STREQ (shell_builtins[i].name, "set"))
-      set_opts = savestring (shell_builtins[i].short_doc);
+      {
+       set_opts = savestring (shell_builtins[i].short_doc);
+       break;
+      }
+
   if (set_opts)
     {
       s = strchr (set_opts, '[');
@@ -1597,61 +2092,45 @@ show_shell_usage (fp, extra)
       t = strchr (s, ']');
       if (t)
        *t = '\0';
-      fprintf (fp, "\t-%s or -o option\n", s);
+      fprintf (fp, _("\t-%s or -o option\n"), s);
       free (set_opts);
     }
 
   if (extra)
     {
-      fprintf (fp, "Type `%s -c \"help set\"' for more information about shell options.\n", shell_name);
-      fprintf (fp, "Type `%s -c help' for more information about shell builtin commands.\n", shell_name);
-      fprintf (fp, "Use the `bashbug' command to report bugs.\n");
+      fprintf (fp, _("Type `%s -c \"help set\"' for more information about shell options.\n"), shell_name);
+      fprintf (fp, _("Type `%s -c help' for more information about shell builtin commands.\n"), shell_name);
+      fprintf (fp, _("Use the `bashbug' command to report bugs.\n"));
+      fprintf (fp, "\n");
+      fprintf (fp, _("bash home page: <http://www.gnu.org/software/bash>\n"));
+      fprintf (fp, _("General help using GNU software: <http://www.gnu.org/gethelp/>\n"));
     }
 }
 
-/* The second and subsequent conditions must match those used to decide
-   whether or not to call getpeername() in isnetconn(). */
-#if defined (HAVE_SYS_SOCKET_H) && defined (HAVE_GETPEERNAME) && !defined (SVR4_2)
-#  include <sys/socket.h>
-#endif
-
-/* Is FD a socket or network connection? */
-static int
-isnetconn (fd)
-     int fd;
+static void
+add_shopt_to_alist (opt, on_or_off)
+     char *opt;
+     int on_or_off;
 {
-#if defined (HAVE_GETPEERNAME) && !defined (SVR4_2) && !defined (__BEOS__)
-  int rv, l;
-  struct sockaddr sa;
-
-  l = sizeof(sa);
-  rv = getpeername(fd, &sa, &l);
-  /* Solaris 2.5 getpeername() returns EINVAL if the fd is not a socket. */
-  return ((rv < 0 && (errno == ENOTSOCK || errno == EINVAL)) ? 0 : 1);
-#else /* !HAVE_GETPEERNAME || SVR4_2 || __BEOS__ */
-#  if defined (SVR4) || defined (SVR4_2)
-  /* Sockets on SVR4 and SVR4.2 are character special (streams) devices. */
-  struct stat sb;
+  if (shopt_ind >= shopt_len)
+    {
+      shopt_len += 8;
+      shopt_alist = (STRING_INT_ALIST *)xrealloc (shopt_alist, shopt_len * sizeof (shopt_alist[0]));
+    }
+  shopt_alist[shopt_ind].word = opt;
+  shopt_alist[shopt_ind].token = on_or_off;
+  shopt_ind++;
+}
 
-  if (isatty (fd))
-    return (0);
-  if (fstat (fd, &sb) < 0)
-    return (0);
-#    if defined (S_ISFIFO)
-  if (S_ISFIFO (sb.st_mode))
-    return (0);
-#    endif /* S_ISFIFO */
-  return (S_ISCHR (sb.st_mode));
-#  else /* !SVR4 && !SVR4_2 */
-#    if defined (S_ISSOCK) && !defined (__BEOS__)
-  struct stat sb;
+static void
+run_shopt_alist ()
+{
+  register int i;
 
-  if (fstat (fd, &sb) < 0)
-    return (0);
-  return (S_ISSOCK (sb.st_mode));
-#    else /* !S_ISSOCK || __BEOS__ */
-  return (0);
-#    endif /* !S_ISSOCK || __BEOS__ */
-#  endif /* !SVR4 && !SVR4_2 */
-#endif /* !HAVE_GETPEERNAME || SVR4_2 || __BEOS__ */
+  for (i = 0; i < shopt_ind; i++)
+    if (shopt_setopt (shopt_alist[i].word, (shopt_alist[i].token == '-')) != EXECUTION_SUCCESS)
+      exit (EX_BADUSAGE);
+  free (shopt_alist);
+  shopt_alist = 0;
+  shopt_ind = shopt_len = 0;
 }