1 /* execute_command.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2002 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
22 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #endif /* _AIX && RISC6000 && !__GNUC__ */
27 #include "chartypes.h"
28 #include "bashtypes.h"
30 # include <sys/file.h>
33 #include "posixstat.h"
36 # include <sys/param.h>
39 #if defined (HAVE_UNISTD_H)
43 #include "posixtime.h"
45 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
46 # include <sys/resource.h>
49 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
50 # include <sys/times.h>
63 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
68 #include "execute_cmd.h"
75 #if defined (COND_COMMAND)
79 #include "builtins/common.h"
80 #include "builtins/builtext.h" /* list of builtins */
82 #include <glob/strmatch.h>
83 #include <tilde/tilde.h>
85 #if defined (BUFFERED_INPUT)
94 # include "bashhist.h"
97 extern int posixly_correct;
98 extern int breaking, continuing, loop_level;
99 extern int expand_aliases;
100 extern int parse_and_execute_level, running_trap, trap_line_number;
101 extern int command_string_index, line_number;
102 extern int dot_found_in_search;
103 extern int already_making_children;
104 extern char *the_printed_command, *shell_name;
105 extern pid_t last_command_subst_pid;
106 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
107 extern char **subshell_argv, **subshell_envp;
108 extern int subshell_argc;
110 extern char *glob_argv_flags;
113 extern int close __P((int));
115 /* Static functions defined and used in this file. */
116 static void close_pipes __P((int, int));
117 static void do_piping __P((int, int));
118 static void bind_lastarg __P((char *));
119 static int shell_control_structure __P((enum command_type));
120 static void cleanup_redirects __P((REDIRECT *));
122 #if defined (JOB_CONTROL)
123 static int restore_signal_mask __P((sigset_t *));
126 static void async_redirect_stdin __P((void));
128 static int builtin_status __P((int));
130 static int execute_for_command __P((FOR_COM *));
131 #if defined (SELECT_COMMAND)
132 static int print_index_and_element __P((int, int, WORD_LIST *));
133 static void indent __P((int, int));
134 static void print_select_list __P((WORD_LIST *, int, int, int));
135 static char *select_query __P((WORD_LIST *, int, char *, int));
136 static int execute_select_command __P((SELECT_COM *));
138 #if defined (DPAREN_ARITHMETIC)
139 static int execute_arith_command __P((ARITH_COM *));
141 #if defined (COND_COMMAND)
142 static int execute_cond_node __P((COND_COM *));
143 static int execute_cond_command __P((COND_COM *));
145 #if defined (COMMAND_TIMING)
146 static int mkfmt __P((char *, int, int, time_t, int));
147 static void print_formatted_time __P((FILE *, char *,
148 time_t, int, time_t, int,
150 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
152 #if defined (ARITH_FOR_COMMAND)
153 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
154 static int execute_arith_for_command __P((ARITH_FOR_COM *));
156 static int execute_case_command __P((CASE_COM *));
157 static int execute_while_command __P((WHILE_COM *));
158 static int execute_until_command __P((WHILE_COM *));
159 static int execute_while_or_until __P((WHILE_COM *, int));
160 static int execute_if_command __P((IF_COM *));
161 static int execute_null_command __P((REDIRECT *, int, int, int, pid_t));
162 static void fix_assignment_words __P((WORD_LIST *));
163 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
164 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
165 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
166 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
168 REDIRECT *, struct fd_bitmap *, int));
169 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
175 static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
176 int, int, int, struct fd_bitmap *, int));
178 static char *getinterp __P((char *, int, int *));
179 static void initialize_subshell __P((void));
180 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
182 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
184 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
186 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
188 /* The line number that the currently executing function starts on. */
189 static int function_line_number;
191 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
192 so that reader_loop can set it to zero before executing a command. */
195 /* The name of the command that is currently being executed.
196 `test' needs this, for example. */
197 char *this_command_name;
199 static COMMAND *currently_executing_command;
201 struct stat SB; /* used for debugging */
203 static int special_builtin_failed;
205 /* For catching RETURN in a function. */
206 int return_catch_flag;
207 int return_catch_value;
208 procenv_t return_catch;
210 /* The value returned by the last synchronous command. */
211 int last_command_exit_value;
213 /* The list of redirections to perform which will undo the redirections
214 that I made in the shell. */
215 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
217 /* The list of redirections to perform which will undo the internal
218 redirections performed by the `exec' builtin. These are redirections
219 that must be undone even when exec discards redirection_undo_list. */
220 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
222 /* Non-zero if we have just forked and are currently running in a subshell
224 int subshell_environment;
226 /* Currently-executing shell function. */
227 SHELL_VAR *this_shell_function;
229 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
231 #define FD_BITMAP_DEFAULT_SIZE 32
233 /* Functions to allocate and deallocate the structures used to pass
234 information from the shell to its children about file descriptors
240 struct fd_bitmap *ret;
242 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
248 ret->bitmap = (char *)xmalloc (size);
249 memset (ret->bitmap, '\0', size);
252 ret->bitmap = (char *)NULL;
257 dispose_fd_bitmap (fdbp)
258 struct fd_bitmap *fdbp;
265 close_fd_bitmap (fdbp)
266 struct fd_bitmap *fdbp;
272 for (i = 0; i < fdbp->size; i++)
281 /* Return the line number of the currently executing command. */
283 executing_line_number ()
285 if (executing && (variable_context == 0 || interactive_shell == 0) && currently_executing_command)
287 if (currently_executing_command->type == cm_simple)
288 return currently_executing_command->value.Simple->line;
289 else if (currently_executing_command->type == cm_cond)
290 return currently_executing_command->value.Cond->line;
291 else if (currently_executing_command->type == cm_arith)
292 return currently_executing_command->value.Arith->line;
293 else if (currently_executing_command->type == cm_arith_for)
294 return currently_executing_command->value.ArithFor->line;
298 else if (running_trap)
299 return trap_line_number;
304 /* Execute the command passed in COMMAND. COMMAND is exactly what
305 read_command () places into GLOBAL_COMMAND. See "command.h" for the
306 details of the command structure.
308 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
309 return values. Executing a command with nothing in it returns
310 EXECUTION_SUCCESS. */
312 execute_command (command)
315 struct fd_bitmap *bitmap;
318 current_fds_to_close = (struct fd_bitmap *)NULL;
319 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
320 begin_unwind_frame ("execute-command");
321 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
323 /* Just do the command, but not asynchronously. */
324 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
326 dispose_fd_bitmap (bitmap);
327 discard_unwind_frame ("execute-command");
329 #if defined (PROCESS_SUBSTITUTION)
330 /* don't unlink fifos if we're in a shell function; wait until the function
332 if (variable_context == 0)
334 #endif /* PROCESS_SUBSTITUTION */
339 /* Return 1 if TYPE is a shell control structure type. */
341 shell_control_structure (type)
342 enum command_type type;
347 #if defined (ARITH_FOR_COMMAND)
350 #if defined (SELECT_COMMAND)
353 #if defined (DPAREN_ARITHMETIC)
356 #if defined (COND_COMMAND)
371 /* A function to use to unwind_protect the redirection undo list
374 cleanup_redirects (list)
377 do_redirections (list, 1, 0, 0);
378 dispose_redirects (list);
382 /* Function to unwind_protect the redirections for functions and builtins. */
384 cleanup_func_redirects (list)
387 do_redirections (list, 1, 0, 0);
392 dispose_exec_redirects ()
394 if (exec_redirection_undo_list)
396 dispose_redirects (exec_redirection_undo_list);
397 exec_redirection_undo_list = (REDIRECT *)NULL;
401 #if defined (JOB_CONTROL)
402 /* A function to restore the signal mask to its proper value when the shell
403 is interrupted or errors occur while creating a pipeline. */
405 restore_signal_mask (set)
408 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
410 #endif /* JOB_CONTROL */
413 /* A debugging function that can be called from gdb, for instance. */
418 int f, fd_table_size;
420 fd_table_size = getdtablesize ();
422 fprintf (stderr, "pid %ld open files:", (long)getpid ());
423 for (i = 3; i < fd_table_size; i++)
425 if ((f = fcntl (i, F_GETFD, 0)) != -1)
426 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
428 fprintf (stderr, "\n");
433 async_redirect_stdin ()
437 fd = open ("/dev/null", O_RDONLY);
444 internal_error ("cannot redirect standard input from /dev/null: %s", strerror (errno));
447 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
449 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
450 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
451 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
452 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
453 from and where it goes. They can have the value of NO_PIPE, which means
455 FDS_TO_CLOSE is a list of file descriptors to close once the child has
456 been forked. This list often contains the unusable sides of pipes, etc.
458 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
459 return values. Executing a command with nothing in it returns
460 EXECUTION_SUCCESS. */
462 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
466 int pipe_in, pipe_out;
467 struct fd_bitmap *fds_to_close;
469 int exec_result, invert, ignore_return, was_error_trap;
470 REDIRECT *my_undo_list, *exec_undo_list;
471 volatile pid_t last_pid;
473 if (command == 0 || breaking || continuing || read_but_dont_execute)
474 return (EXECUTION_SUCCESS);
476 run_pending_traps ();
478 if (running_trap == 0)
479 currently_executing_command = command;
481 invert = (command->flags & CMD_INVERT_RETURN) != 0;
483 /* If we're inverting the return value and `set -e' has been executed,
484 we don't want a failing command to inadvertently cause the shell
486 if (exit_immediately_on_error && invert) /* XXX */
487 command->flags |= CMD_IGNORE_RETURN; /* XXX */
489 exec_result = EXECUTION_SUCCESS;
491 /* If a command was being explicitly run in a subshell, or if it is
492 a shell control-structure, and it has a pipe, then we do the command
494 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
495 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
497 if (command->type == cm_subshell ||
498 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
499 (shell_control_structure (command->type) &&
500 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
504 /* Fork a subshell, turn off the subshell bit, turn off job
505 control and call execute_command () on the command again. */
506 paren_pid = make_child (savestring (make_command_string (command)),
509 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
513 close_pipes (pipe_in, pipe_out);
515 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
518 /* If we are part of a pipeline, and not the end of the pipeline,
519 then we should simply return and let the last command in the
520 pipe be waited for. If we are not in a pipeline, or are the
521 last command in the pipeline, then we wait for the subshell
522 and return its exit status as usual. */
523 if (pipe_out != NO_PIPE)
524 return (EXECUTION_SUCCESS);
526 stop_pipeline (asynchronous, (COMMAND *)NULL);
528 if (asynchronous == 0)
530 last_command_exit_value = wait_for (paren_pid);
532 /* If we have to, invert the return value. */
534 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
536 : EXECUTION_SUCCESS);
538 exec_result = last_command_exit_value;
540 return (last_command_exit_value = exec_result);
544 DESCRIBE_PID (paren_pid);
546 run_pending_traps ();
548 return (EXECUTION_SUCCESS);
553 #if defined (COMMAND_TIMING)
554 if (command->flags & CMD_TIME_PIPELINE)
558 command->flags |= CMD_FORCE_SUBSHELL;
559 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
563 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
564 if (running_trap == 0)
565 currently_executing_command = (COMMAND *)NULL;
567 return (exec_result);
569 #endif /* COMMAND_TIMING */
571 if (shell_control_structure (command->type) && command->redirects)
572 stdin_redir = stdin_redirects (command->redirects);
574 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
576 if (do_redirections (command->redirects, 1, 1, 0) != 0)
578 cleanup_redirects (redirection_undo_list);
579 redirection_undo_list = (REDIRECT *)NULL;
580 dispose_exec_redirects ();
581 return (EXECUTION_FAILURE);
584 if (redirection_undo_list)
586 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
587 dispose_redirects (redirection_undo_list);
588 redirection_undo_list = (REDIRECT *)NULL;
591 my_undo_list = (REDIRECT *)NULL;
593 if (exec_redirection_undo_list)
595 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
596 dispose_redirects (exec_redirection_undo_list);
597 exec_redirection_undo_list = (REDIRECT *)NULL;
600 exec_undo_list = (REDIRECT *)NULL;
602 if (my_undo_list || exec_undo_list)
603 begin_unwind_frame ("loop_redirections");
606 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
609 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
611 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
615 switch (command->type)
619 /* We can't rely on this variable retaining its value across a
620 call to execute_simple_command if a longjmp occurs as the
621 result of a `return' builtin. This is true for sure with gcc. */
622 last_pid = last_made_pid;
623 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
625 if (ignore_return && command->value.Simple)
626 command->value.Simple->flags |= CMD_IGNORE_RETURN;
627 if (command->flags & CMD_STDIN_REDIR)
628 command->value.Simple->flags |= CMD_STDIN_REDIR;
630 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
631 asynchronous, fds_to_close);
633 /* The temporary environment should be used for only the simple
634 command immediately following its definition. */
635 dispose_used_env_vars ();
637 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
638 /* Reclaim memory allocated with alloca () on machines which
639 may be using the alloca emulation code. */
641 #endif /* (ultrix && mips) || C_ALLOCA */
643 /* If we forked to do the command, then we must wait_for ()
646 /* XXX - this is something to watch out for if there are problems
647 when the shell is compiled without job control. */
648 if (already_making_children && pipe_out == NO_PIPE &&
649 last_pid != last_made_pid)
651 stop_pipeline (asynchronous, (COMMAND *)NULL);
655 DESCRIBE_PID (last_made_pid);
658 #if !defined (JOB_CONTROL)
659 /* Do not wait for asynchronous processes started from
661 if (last_made_pid != last_asynchronous_pid)
663 /* When executing a shell function that executes other
664 commands, this causes the last simple command in
665 the function to be waited for twice. */
666 exec_result = wait_for (last_made_pid);
667 #if defined (RECYCLES_PIDS)
668 /* LynxOS, for one, recycles pids very quickly -- so quickly
669 that a new process may have the same pid as the last one
670 created. This has been reported to fix the problem. */
671 if (exec_result == 0)
672 last_made_pid = NO_PID;
677 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
679 last_command_exit_value = exec_result;
683 if (ignore_return == 0 && invert == 0 &&
684 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
685 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
687 last_command_exit_value = exec_result;
688 run_pending_traps ();
689 jump_to_top_level (EXITPROG);
696 command->value.For->flags |= CMD_IGNORE_RETURN;
697 exec_result = execute_for_command (command->value.For);
700 #if defined (ARITH_FOR_COMMAND)
703 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
704 exec_result = execute_arith_for_command (command->value.ArithFor);
708 #if defined (SELECT_COMMAND)
711 command->value.Select->flags |= CMD_IGNORE_RETURN;
712 exec_result = execute_select_command (command->value.Select);
718 command->value.Case->flags |= CMD_IGNORE_RETURN;
719 exec_result = execute_case_command (command->value.Case);
724 command->value.While->flags |= CMD_IGNORE_RETURN;
725 exec_result = execute_while_command (command->value.While);
730 command->value.While->flags |= CMD_IGNORE_RETURN;
731 exec_result = execute_until_command (command->value.While);
736 command->value.If->flags |= CMD_IGNORE_RETURN;
737 exec_result = execute_if_command (command->value.If);
742 /* This code can be executed from either of two paths: an explicit
743 '{}' command, or via a function call. If we are executed via a
744 function call, we have already taken care of the function being
745 executed in the background (down there in execute_simple_command ()),
746 and this command should *not* be marked as asynchronous. If we
747 are executing a regular '{}' group command, and asynchronous == 1,
748 we must want to execute the whole command in the background, so we
749 need a subshell, and we want the stuff executed in that subshell
750 (this group command) to be executed in the foreground of that
751 subshell (i.e. there will not be *another* subshell forked).
753 What we do is to force a subshell if asynchronous, and then call
754 execute_command_internal again with asynchronous still set to 1,
755 but with the original group command, so the printed command will
758 The code above that handles forking off subshells will note that
759 both subshell and async are on, and turn off async in the child
760 after forking the subshell (but leave async set in the parent, so
761 the normal call to describe_pid is made). This turning off
762 async is *crucial*; if it is not done, this will fall into an
763 infinite loop of executions through this spot in subshell after
764 subshell until the process limit is exhausted. */
768 command->flags |= CMD_FORCE_SUBSHELL;
770 execute_command_internal (command, 1, pipe_in, pipe_out,
775 if (ignore_return && command->value.Group->command)
776 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
778 execute_command_internal (command->value.Group->command,
779 asynchronous, pipe_in, pipe_out,
785 exec_result = execute_connection (command, asynchronous,
786 pipe_in, pipe_out, fds_to_close);
789 #if defined (DPAREN_ARITHMETIC)
792 command->value.Arith->flags |= CMD_IGNORE_RETURN;
793 exec_result = execute_arith_command (command->value.Arith);
797 #if defined (COND_COMMAND)
800 command->value.Cond->flags |= CMD_IGNORE_RETURN;
801 exec_result = execute_cond_command (command->value.Cond);
805 case cm_function_def:
806 exec_result = execute_intern_function (command->value.Function_def->name,
807 command->value.Function_def->command);
811 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
816 do_redirections (my_undo_list, 1, 0, 0);
817 dispose_redirects (my_undo_list);
821 dispose_redirects (exec_undo_list);
823 if (my_undo_list || exec_undo_list)
824 discard_unwind_frame ("loop_redirections");
826 /* Invert the return value if we have to */
828 exec_result = (exec_result == EXECUTION_SUCCESS)
832 last_command_exit_value = exec_result;
833 run_pending_traps ();
834 if (running_trap == 0)
835 currently_executing_command = (COMMAND *)NULL;
836 return (last_command_exit_value);
839 #if defined (COMMAND_TIMING)
841 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
842 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
843 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
844 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
847 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
848 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
850 static int precs[] = { 0, 100, 10, 1 };
852 /* Expand one `%'-prefixed escape sequence from a time format string. */
854 mkfmt (buf, prec, lng, sec, sec_fraction)
861 char abuf[INT_STRLEN_BOUND(time_t) + 1];
865 abuf[sizeof(abuf) - 1] = '\0';
867 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
872 aind = sizeof(abuf) - 2;
874 abuf[aind--] = (min % 10) + '0';
878 buf[ind++] = abuf[aind++];
882 /* Now add the seconds. */
883 aind = sizeof (abuf) - 2;
885 abuf[aind--] = (sec % 10) + '0';
889 buf[ind++] = abuf[aind++];
891 /* We want to add a decimal point and PREC places after it if PREC is
892 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
897 for (aind = 1; aind <= prec; aind++)
899 buf[ind++] = (sec_fraction / precs[aind]) + '0';
900 sec_fraction %= precs[aind];
911 /* Interpret the format string FORMAT, interpolating the following escape
915 where the optional `prec' is a precision, meaning the number of
916 characters after the decimal point, the optional `l' means to format
917 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
918 and the last character is one of
920 R number of seconds of `real' time
921 U number of seconds of `user' time
922 S number of seconds of `system' time
924 An occurrence of `%%' in the format string is translated to a `%'. The
925 result is printed to FP, a pointer to a FILE. The other variables are
926 the seconds and thousandths of a second of real, user, and system time,
929 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
940 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
945 len = strlen (format);
946 ssize = (len + 64) - (len % 64);
947 str = (char *)xmalloc (ssize);
950 for (s = format; *s; s++)
952 if (*s != '%' || s[1] == '\0')
954 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
957 else if (s[1] == '%')
960 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
963 else if (s[1] == 'P')
969 sum_frac = (cpu % 100) * 10;
970 len = mkfmt (ts, 2, 0, sum, sum_frac);
971 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
972 strcpy (str + sindex, ts);
977 prec = 3; /* default is three places past the decimal point. */
978 lng = 0; /* default is to not use minutes or append `s' */
980 if (DIGIT (*s)) /* `precision' */
983 if (prec > 3) prec = 3;
985 if (*s == 'l') /* `length extender' */
990 if (*s == 'R' || *s == 'E')
991 len = mkfmt (ts, prec, lng, rs, rsf);
993 len = mkfmt (ts, prec, lng, us, usf);
995 len = mkfmt (ts, prec, lng, ss, ssf);
998 internal_error ("bad format character in time format: %c", *s);
1002 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1003 strcpy (str + sindex, ts);
1009 fprintf (fp, "%s\n", str);
1016 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1018 int asynchronous, pipe_in, pipe_out;
1019 struct fd_bitmap *fds_to_close;
1021 int rv, posix_time, old_flags;
1027 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1028 struct timeval real, user, sys;
1029 struct timeval before, after;
1030 struct timezone dtz;
1031 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1033 # if defined (HAVE_TIMES)
1034 clock_t tbefore, tafter, real, user, sys;
1035 struct tms before, after;
1039 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1040 gettimeofday (&before, &dtz);
1041 getrusage (RUSAGE_SELF, &selfb);
1042 getrusage (RUSAGE_CHILDREN, &kidsb);
1044 # if defined (HAVE_TIMES)
1045 tbefore = times (&before);
1049 posix_time = (command->flags & CMD_TIME_POSIX);
1051 old_flags = command->flags;
1052 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1053 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1054 command->flags = old_flags;
1057 rsf = usf = ssf = cpu = 0;
1059 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1060 gettimeofday (&after, &dtz);
1061 getrusage (RUSAGE_SELF, &selfa);
1062 getrusage (RUSAGE_CHILDREN, &kidsa);
1064 difftimeval (&real, &before, &after);
1065 timeval_to_secs (&real, &rs, &rsf);
1067 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1068 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1069 timeval_to_secs (&user, &us, &usf);
1071 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1072 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1073 timeval_to_secs (&sys, &ss, &ssf);
1075 cpu = timeval_to_cpu (&real, &user, &sys);
1077 # if defined (HAVE_TIMES)
1078 tafter = times (&after);
1080 real = tafter - tbefore;
1081 clock_t_to_secs (real, &rs, &rsf);
1083 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1084 clock_t_to_secs (user, &us, &usf);
1086 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1087 clock_t_to_secs (sys, &ss, &ssf);
1089 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1093 rsf = usf = ssf = cpu = 0;
1098 time_format = POSIX_TIMEFORMAT;
1099 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1100 time_format = BASH_TIMEFORMAT;
1102 if (time_format && *time_format)
1103 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1107 #endif /* COMMAND_TIMING */
1109 /* Execute a command that's supposed to be in a subshell. This must be
1110 called after make_child and we must be running in the child process.
1111 The caller will return or exit() immediately with the value this returns. */
1113 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1116 int pipe_in, pipe_out;
1117 struct fd_bitmap *fds_to_close;
1119 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1123 USE_VAR(user_subshell);
1126 USE_VAR(asynchronous);
1128 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1129 pipe_in == NO_PIPE &&
1130 stdin_redirects (command->redirects) == 0);
1132 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1133 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1135 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1137 /* If a command is asynchronous in a subshell (like ( foo ) & or
1138 the special case of an asynchronous GROUP command where the
1139 the subshell bit is turned on down in case cm_group: below),
1140 turn off `asynchronous', so that two subshells aren't spawned.
1142 This seems semantically correct to me. For example,
1143 ( foo ) & seems to say ``do the command `foo' in a subshell
1144 environment, but don't wait for that subshell to finish'',
1145 and "{ foo ; bar ; } &" seems to me to be like functions or
1146 builtins in the background, which executed in a subshell
1147 environment. I just don't see the need to fork two subshells. */
1149 /* Don't fork again, we are already in a subshell. A `doubly
1150 async' shell is not interactive, however. */
1153 #if defined (JOB_CONTROL)
1154 /* If a construct like ( exec xxx yyy ) & is given while job
1155 control is active, we want to prevent exec from putting the
1156 subshell back into the original process group, carefully
1157 undoing all the work we just did in make_child. */
1159 #endif /* JOB_CONTROL */
1160 ois = interactive_shell;
1161 interactive_shell = 0;
1162 /* This test is to prevent alias expansion by interactive shells that
1163 run `(command) &' but to allow scripts that have enabled alias
1164 expansion with `shopt -s expand_alias' to continue to expand
1166 if (ois != interactive_shell)
1171 /* Subshells are neither login nor interactive. */
1172 login_shell = interactive = 0;
1174 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
1176 reset_terminating_signals (); /* in sig.c */
1177 /* Cancel traps, in trap.c. */
1178 restore_original_signals ();
1180 setup_async_signals ();
1182 #if defined (JOB_CONTROL)
1183 set_sigchld_handler ();
1184 #endif /* JOB_CONTROL */
1186 set_sigint_handler ();
1188 #if defined (JOB_CONTROL)
1189 /* Delete all traces that there were any jobs running. This is
1190 only for subshells. */
1191 without_job_control ();
1192 #endif /* JOB_CONTROL */
1195 close_fd_bitmap (fds_to_close);
1197 do_piping (pipe_in, pipe_out);
1199 /* If this is a user subshell, set a flag if stdin was redirected.
1200 This is used later to decide whether to redirect fd 0 to
1201 /dev/null for async commands in the subshell. This adds more
1202 sh compatibility, but I'm not sure it's the right thing to do. */
1205 stdin_redir = stdin_redirects (command->redirects);
1206 restore_default_signal (0);
1209 /* If this is an asynchronous command (command &), we want to
1210 redirect the standard input from /dev/null in the absence of
1211 any specific redirection involving stdin. */
1212 if (should_redir_stdin && stdin_redir == 0)
1213 async_redirect_stdin ();
1215 /* Do redirections, then dispose of them before recursive call. */
1216 if (command->redirects)
1218 if (do_redirections (command->redirects, 1, 0, 0) != 0)
1219 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1221 dispose_redirects (command->redirects);
1222 command->redirects = (REDIRECT *)NULL;
1225 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1227 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1228 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1229 tcom->flags |= CMD_IGNORE_RETURN;
1231 /* If this is a simple command, tell execute_disk_command that it
1232 might be able to get away without forking and simply exec.
1233 This means things like ( sleep 10 ) will only cause one fork.
1234 If we're timing the command or inverting its return value, however,
1235 we cannot do this optimization. */
1236 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1237 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1238 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1240 tcom->flags |= CMD_NO_FORK;
1241 if (tcom->type == cm_simple)
1242 tcom->value.Simple->flags |= CMD_NO_FORK;
1245 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1246 tcom->flags &= ~CMD_INVERT_RETURN;
1248 /* If we're inside a function while executing this subshell, we
1249 need to handle a possible `return'. */
1251 if (return_catch_flag)
1252 function_value = setjmp (return_catch);
1255 return_code = return_catch_value;
1257 return_code = execute_command_internal
1258 (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1260 /* If we are asked to, invert the return value. */
1262 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1263 : EXECUTION_SUCCESS;
1265 /* If we were explicitly placed in a subshell with (), we need
1266 to do the `shell cleanup' things, such as running traps[0]. */
1267 if (user_subshell && signal_is_trapped (0))
1269 last_command_exit_value = return_code;
1270 return_code = run_exit_trap ();
1273 return (return_code);
1278 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1280 int asynchronous, pipe_in, pipe_out;
1281 struct fd_bitmap *fds_to_close;
1283 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1285 struct fd_bitmap *fd_bitmap;
1287 #if defined (JOB_CONTROL)
1289 BLOCK_CHILD (set, oset);
1290 #endif /* JOB_CONTROL */
1292 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1297 while (cmd && cmd->type == cm_connection &&
1298 cmd->value.Connection && cmd->value.Connection->connector == '|')
1300 /* Make a pipeline between the two commands. */
1301 if (pipe (fildes) < 0)
1303 sys_error ("pipe error");
1304 #if defined (JOB_CONTROL)
1305 terminate_current_pipeline ();
1306 kill_current_pipeline ();
1307 #endif /* JOB_CONTROL */
1308 last_command_exit_value = EXECUTION_FAILURE;
1309 /* The unwind-protects installed below will take care
1310 of closing all of the open file descriptors. */
1311 throw_to_top_level ();
1312 return (EXECUTION_FAILURE); /* XXX */
1315 /* Here is a problem: with the new file close-on-exec
1316 code, the read end of the pipe (fildes[0]) stays open
1317 in the first process, so that process will never get a
1318 SIGPIPE. There is no way to signal the first process
1319 that it should close fildes[0] after forking, so it
1320 remains open. No SIGPIPE is ever sent because there
1321 is still a file descriptor open for reading connected
1322 to the pipe. We take care of that here. This passes
1323 around a bitmap of file descriptors that must be
1324 closed after making a child process in execute_simple_command. */
1326 /* We need fd_bitmap to be at least as big as fildes[0].
1327 If fildes[0] is less than fds_to_close->size, then
1328 use fds_to_close->size. */
1329 new_bitmap_size = (fildes[0] < fds_to_close->size)
1330 ? fds_to_close->size
1333 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1335 /* Now copy the old information into the new bitmap. */
1336 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1338 /* And mark the pipe file descriptors to be closed. */
1339 fd_bitmap->bitmap[fildes[0]] = 1;
1341 /* In case there are pipe or out-of-processes errors, we
1342 want all these file descriptors to be closed when
1343 unwind-protects are run, and the storage used for the
1344 bitmaps freed up. */
1345 begin_unwind_frame ("pipe-file-descriptors");
1346 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1347 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1349 add_unwind_protect (close, prev);
1350 dummyfd = fildes[1];
1351 add_unwind_protect (close, dummyfd);
1353 #if defined (JOB_CONTROL)
1354 add_unwind_protect (restore_signal_mask, &oset);
1355 #endif /* JOB_CONTROL */
1357 if (ignore_return && cmd->value.Connection->first)
1358 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1359 execute_command_internal (cmd->value.Connection->first, asynchronous,
1360 prev, fildes[1], fd_bitmap);
1368 dispose_fd_bitmap (fd_bitmap);
1369 discard_unwind_frame ("pipe-file-descriptors");
1371 cmd = cmd->value.Connection->second;
1374 /* Now execute the rightmost command in the pipeline. */
1375 if (ignore_return && cmd)
1376 cmd->flags |= CMD_IGNORE_RETURN;
1377 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1382 #if defined (JOB_CONTROL)
1383 UNBLOCK_CHILD (oset);
1386 return (exec_result);
1390 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1392 int asynchronous, pipe_in, pipe_out;
1393 struct fd_bitmap *fds_to_close;
1396 COMMAND *tc, *second;
1397 int ignore_return, exec_result;
1399 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1401 switch (command->value.Connection->connector)
1403 /* Do the first command asynchronously. */
1405 tc = command->value.Connection->first;
1407 return (EXECUTION_SUCCESS);
1412 tc->flags |= CMD_IGNORE_RETURN;
1413 tc->flags |= CMD_AMPERSAND;
1415 /* If this shell was compiled without job control support,
1416 if we are currently in a subshell via `( xxx )', or if job
1417 control is not active then the standard input for an
1418 asynchronous command is forced to /dev/null. */
1419 #if defined (JOB_CONTROL)
1420 if ((subshell_environment || !job_control) && !stdin_redir)
1423 #endif /* JOB_CONTROL */
1424 tc->flags |= CMD_STDIN_REDIR;
1426 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1428 if (tc->flags & CMD_STDIN_REDIR)
1429 tc->flags &= ~CMD_STDIN_REDIR;
1431 second = command->value.Connection->second;
1435 second->flags |= CMD_IGNORE_RETURN;
1437 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1442 /* Just call execute command on both sides. */
1446 if (command->value.Connection->first)
1447 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1448 if (command->value.Connection->second)
1449 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1452 execute_command (command->value.Connection->first);
1454 exec_result = execute_command_internal (command->value.Connection->second,
1455 asynchronous, pipe_in, pipe_out,
1460 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1467 /* If we have something like `a && b &' or `a || b &', run the
1468 && or || stuff in a subshell. Force a subshell and just call
1469 execute_command_internal again. Leave asynchronous on
1470 so that we get a report from the parent shell about the
1472 command->flags |= CMD_FORCE_SUBSHELL;
1473 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1477 /* Execute the first command. If the result of that is successful
1478 and the connector is AND_AND, or the result is not successful
1479 and the connector is OR_OR, then execute the second command,
1480 otherwise return. */
1482 if (command->value.Connection->first)
1483 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1485 exec_result = execute_command (command->value.Connection->first);
1487 if (((command->value.Connection->connector == AND_AND) &&
1488 (exec_result == EXECUTION_SUCCESS)) ||
1489 ((command->value.Connection->connector == OR_OR) &&
1490 (exec_result != EXECUTION_SUCCESS)))
1492 if (ignore_return && command->value.Connection->second)
1493 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1495 exec_result = execute_command (command->value.Connection->second);
1500 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
1501 jump_to_top_level (DISCARD);
1502 exec_result = EXECUTION_FAILURE;
1511 if (!interactive_shell) \
1512 reap_dead_jobs (); \
1516 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1519 execute_for_command (for_command)
1520 FOR_COM *for_command;
1522 register WORD_LIST *releaser, *list;
1527 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1530 if (check_identifier (for_command->name, 1) == 0)
1532 if (posixly_correct && interactive_shell == 0)
1534 last_command_exit_value = EX_USAGE;
1535 jump_to_top_level (EXITPROG);
1537 return (EXECUTION_FAILURE);
1541 identifier = for_command->name->word;
1543 list = releaser = expand_words_no_vars (for_command->map_list);
1545 begin_unwind_frame ("for");
1546 add_unwind_protect (dispose_words, releaser);
1549 if (lexical_scoping)
1551 old_value = copy_variable (find_variable (identifier));
1553 add_unwind_protect (dispose_variable, old_value);
1557 if (for_command->flags & CMD_IGNORE_RETURN)
1558 for_command->action->flags |= CMD_IGNORE_RETURN;
1560 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1563 this_command_name = (char *)NULL;
1564 v = bind_variable (identifier, list->word->word);
1565 if (readonly_p (v) || noassign_p (v))
1567 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1569 last_command_exit_value = EXECUTION_FAILURE;
1570 jump_to_top_level (FORCE_EOF);
1574 run_unwind_frame ("for");
1576 return (EXECUTION_FAILURE);
1579 retval = execute_command (for_command->action);
1600 if (lexical_scoping)
1603 unbind_variable (identifier);
1606 SHELL_VAR *new_value;
1608 new_value = bind_variable (identifier, value_cell(old_value));
1609 new_value->attributes = old_value->attributes;
1610 dispose_variable (old_value);
1615 dispose_words (releaser);
1616 discard_unwind_frame ("for");
1620 #if defined (ARITH_FOR_COMMAND)
1621 /* Execute an arithmetic for command. The syntax is
1623 for (( init ; step ; test ))
1628 The execution should be exactly equivalent to
1631 while eval \(\( test \)\) ; do
1637 eval_arith_for_expr (l, okp)
1644 new = expand_words_no_vars (l);
1647 if (echo_command_at_execute)
1648 xtrace_print_arith_cmd (new);
1649 this_command_name = "(("; /* )) for expression error messages */
1650 if (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
1652 expresult = evalexp (new->word->word, okp);
1653 dispose_words (new);
1665 execute_arith_for_command (arith_for_command)
1666 ARITH_FOR_COM *arith_for_command;
1669 int expok, body_status, arith_lineno, save_lineno;
1671 body_status = EXECUTION_SUCCESS;
1674 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1675 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1677 this_command_name = "(("; /* )) for expression error messages */
1679 /* save the starting line number of the command so we can reset
1680 line_number before executing each expression -- for $LINENO
1681 and the DEBUG trap. */
1682 arith_lineno = arith_for_command->line;
1683 if (variable_context && interactive_shell)
1684 line_number = arith_lineno -= function_line_number;
1686 /* Evaluate the initialization expression. */
1687 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1689 return (EXECUTION_FAILURE);
1693 /* Evaluate the test expression. */
1694 save_lineno = line_number;
1695 line_number = arith_lineno;
1696 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
1697 line_number = save_lineno;
1701 body_status = EXECUTION_FAILURE;
1708 /* Execute the body of the arithmetic for command. */
1710 body_status = execute_command (arith_for_command->action);
1713 /* Handle any `break' or `continue' commands executed by the body. */
1727 /* Evaluate the step expression. */
1728 save_lineno = line_number;
1729 line_number = arith_lineno;
1730 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
1731 line_number = save_lineno;
1735 body_status = EXECUTION_FAILURE;
1741 return (body_status);
1745 #if defined (SELECT_COMMAND)
1746 static int LINES, COLS, tabsize;
1748 #define RP_SPACE ") "
1749 #define RP_SPACE_LEN 2
1751 /* XXX - does not handle numbers > 1000000 at all. */
1752 #define NUMBER_LEN(s) \
1756 : ((s < 10000) ? 4 \
1757 : ((s < 100000) ? 5 \
1761 print_index_and_element (len, ind, list)
1765 register WORD_LIST *l;
1770 for (i = ind, l = list; l && --i; l = l->next)
1772 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1773 return (STRLEN (l->word->word));
1782 if ((to / tabsize) > (from / tabsize))
1784 putc ('\t', stderr);
1785 from += tabsize - from % tabsize;
1796 print_select_list (list, list_len, max_elem_len, indices_len)
1798 int list_len, max_elem_len, indices_len;
1800 int ind, row, elem_len, pos, cols, rows;
1801 int first_column_indices_len, other_indices_len;
1805 putc ('\n', stderr);
1809 cols = max_elem_len ? COLS / max_elem_len : 1;
1812 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1813 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1821 first_column_indices_len = NUMBER_LEN (rows);
1822 other_indices_len = indices_len;
1824 for (row = 0; row < rows; row++)
1830 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1831 elem_len = print_index_and_element (indices_len, ind + 1, list);
1832 elem_len += indices_len + RP_SPACE_LEN;
1834 if (ind >= list_len)
1836 indent (pos + elem_len, pos + max_elem_len);
1837 pos += max_elem_len;
1839 putc ('\n', stderr);
1843 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1844 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1845 If the number is between 1 and LIST_LEN, return that selection. If EOF
1846 is read, return a null string. If a blank line is entered, or an invalid
1847 number is entered, the loop is executed again. */
1849 select_query (list, list_len, prompt, print_menu)
1855 int max_elem_len, indices_len, len;
1858 char *repl_string, *t;
1860 t = get_string_value ("LINES");
1861 LINES = (t && *t) ? atoi (t) : 24;
1862 t = get_string_value ("COLUMNS");
1863 COLS = (t && *t) ? atoi (t) : 80;
1866 t = get_string_value ("TABSIZE");
1867 tabsize = (t && *t) ? atoi (t) : 8;
1875 for (l = list; l; l = l->next)
1877 len = STRLEN (l->word->word);
1878 if (len > max_elem_len)
1881 indices_len = NUMBER_LEN (list_len);
1882 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1887 print_select_list (list, list_len, max_elem_len, indices_len);
1888 fprintf (stderr, "%s", prompt);
1892 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1895 return ((char *)NULL);
1897 repl_string = get_string_value ("REPLY");
1898 if (*repl_string == 0)
1903 if (legal_number (repl_string, &reply) == 0)
1905 if (reply < 1 || reply > list_len)
1908 for (l = list; l && --reply; l = l->next)
1910 return (l->word->word);
1914 /* Execute a SELECT command. The syntax is:
1915 SELECT word IN list DO command_list DONE
1916 Only `break' or `return' in command_list will terminate
1919 execute_select_command (select_command)
1920 SELECT_COM *select_command;
1922 WORD_LIST *releaser, *list;
1924 char *identifier, *ps3_prompt, *selection;
1925 int retval, list_len, show_menu;
1927 if (check_identifier (select_command->name, 1) == 0)
1928 return (EXECUTION_FAILURE);
1931 identifier = select_command->name->word;
1933 /* command and arithmetic substitution, parameter and variable expansion,
1934 word splitting, pathname expansion, and quote removal. */
1935 list = releaser = expand_words_no_vars (select_command->map_list);
1936 list_len = list_length (list);
1937 if (list == 0 || list_len == 0)
1940 dispose_words (list);
1941 return (EXECUTION_SUCCESS);
1944 begin_unwind_frame ("select");
1945 add_unwind_protect (dispose_words, releaser);
1947 if (select_command->flags & CMD_IGNORE_RETURN)
1948 select_command->action->flags |= CMD_IGNORE_RETURN;
1950 retval = EXECUTION_SUCCESS;
1955 ps3_prompt = get_string_value ("PS3");
1956 if (ps3_prompt == 0)
1960 selection = select_query (list, list_len, ps3_prompt, show_menu);
1964 /* select_query returns EXECUTION_FAILURE if the read builtin
1965 fails, so we want to return failure in this case. */
1966 retval = EXECUTION_FAILURE;
1970 v = bind_variable (identifier, selection);
1971 if (readonly_p (v) || noassign_p (v))
1973 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1975 last_command_exit_value = EXECUTION_FAILURE;
1976 jump_to_top_level (FORCE_EOF);
1980 run_unwind_frame ("select");
1981 return (EXECUTION_FAILURE);
1985 retval = execute_command (select_command->action);
2003 #if defined (KSH_COMPATIBLE_SELECT)
2005 selection = get_string_value ("REPLY");
2006 if (selection && *selection == '\0')
2013 run_unwind_frame ("select");
2016 #endif /* SELECT_COMMAND */
2018 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2019 The pattern_list is a linked list of pattern clauses; each clause contains
2020 some patterns to compare word_desc against, and an associated command to
2023 execute_case_command (case_command)
2024 CASE_COM *case_command;
2026 register WORD_LIST *list;
2027 WORD_LIST *wlist, *es;
2028 PATTERN_LIST *clauses;
2029 char *word, *pattern;
2030 int retval, match, ignore_return;
2032 /* Posix.2 specifies that the WORD is tilde expanded. */
2033 if (member ('~', case_command->word->word))
2035 word = bash_tilde_expand (case_command->word->word, 0);
2036 free (case_command->word->word);
2037 case_command->word->word = word;
2040 wlist = expand_word_unsplit (case_command->word, 0);
2041 word = wlist ? string_list (wlist) : savestring ("");
2042 dispose_words (wlist);
2044 retval = EXECUTION_SUCCESS;
2045 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2047 begin_unwind_frame ("case");
2048 add_unwind_protect ((Function *)xfree, word);
2050 #define EXIT_CASE() goto exit_case_command
2052 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2055 for (list = clauses->patterns; list; list = list->next)
2057 /* Posix.2 specifies to tilde expand each member of the pattern
2059 if (member ('~', list->word->word))
2061 pattern = bash_tilde_expand (list->word->word, 0);
2062 free (list->word->word);
2063 list->word->word = pattern;
2066 es = expand_word_leave_quoted (list->word, 0);
2068 if (es && es->word && es->word->word && *(es->word->word))
2069 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2072 pattern = (char *)xmalloc (1);
2076 /* Since the pattern does not undergo quote removal (as per
2077 Posix.2, section 3.9.4.3), the strmatch () call must be able
2078 to recognize backslashes as escape characters. */
2079 match = strmatch (pattern, word, FNMATCH_EXTFLAG) != FNM_NOMATCH;
2086 if (clauses->action && ignore_return)
2087 clauses->action->flags |= CMD_IGNORE_RETURN;
2088 retval = execute_command (clauses->action);
2098 discard_unwind_frame ("case");
2105 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2106 Repeatedly execute action while executing test produces
2107 EXECUTION_SUCCESS. */
2109 execute_while_command (while_command)
2110 WHILE_COM *while_command;
2112 return (execute_while_or_until (while_command, CMD_WHILE));
2115 /* UNTIL is just like WHILE except that the test result is negated. */
2117 execute_until_command (while_command)
2118 WHILE_COM *while_command;
2120 return (execute_while_or_until (while_command, CMD_UNTIL));
2123 /* The body for both while and until. The only difference between the
2124 two is that the test value is treated differently. TYPE is
2125 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2126 be EXECUTION_SUCCESS if no commands in the body are executed, and
2127 the status of the last command executed in the body otherwise. */
2129 execute_while_or_until (while_command, type)
2130 WHILE_COM *while_command;
2133 int return_value, body_status;
2135 body_status = EXECUTION_SUCCESS;
2138 while_command->test->flags |= CMD_IGNORE_RETURN;
2139 if (while_command->flags & CMD_IGNORE_RETURN)
2140 while_command->action->flags |= CMD_IGNORE_RETURN;
2144 return_value = execute_command (while_command->test);
2147 /* Need to handle `break' in the test when we would break out of the
2148 loop. The job control code will set `breaking' to loop_level
2149 when a job in a loop is stopped with SIGTSTP. If the stopped job
2150 is in the loop test, `breaking' will not be reset unless we do
2151 this, and the shell will cease to execute commands. */
2152 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2158 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2166 body_status = execute_command (while_command->action);
2184 return (body_status);
2187 /* IF test THEN command [ELSE command].
2188 IF also allows ELIF in the place of ELSE IF, but
2189 the parser makes *that* stupidity transparent. */
2191 execute_if_command (if_command)
2196 if_command->test->flags |= CMD_IGNORE_RETURN;
2197 return_value = execute_command (if_command->test);
2199 if (return_value == EXECUTION_SUCCESS)
2203 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2204 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2206 return (execute_command (if_command->true_case));
2212 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2213 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2215 return (execute_command (if_command->false_case));
2219 #if defined (DPAREN_ARITHMETIC)
2221 execute_arith_command (arith_command)
2222 ARITH_COM *arith_command;
2230 this_command_name = "(("; /* )) */
2231 /* If we're in a function, update the line number information. */
2232 if (variable_context && interactive_shell)
2233 line_number = arith_command->line - function_line_number;
2235 /* Run the debug trap before each arithmetic command, but do it after we
2236 update the line number information and before we expand the various
2237 words in the expression. */
2238 if (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2241 new = expand_words (arith_command->exp);
2243 /* If we're tracing, make a new word list with `((' at the front and `))'
2244 at the back and print it. */
2245 if (echo_command_at_execute)
2246 xtrace_print_arith_cmd (new);
2248 expresult = evalexp (new->word->word, &expok);
2249 dispose_words (new);
2252 return (EXECUTION_FAILURE);
2254 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2256 #endif /* DPAREN_ARITHMETIC */
2258 #if defined (COND_COMMAND)
2260 static char *nullstr = "";
2263 execute_cond_node (cond)
2266 int result, invert, patmatch;
2269 invert = (cond->flags & CMD_INVERT_RETURN);
2271 if (cond->type == COND_EXPR)
2272 result = execute_cond_node (cond->left);
2273 else if (cond->type == COND_OR)
2275 result = execute_cond_node (cond->left);
2276 if (result != EXECUTION_SUCCESS)
2277 result = execute_cond_node (cond->right);
2279 else if (cond->type == COND_AND)
2281 result = execute_cond_node (cond->left);
2282 if (result == EXECUTION_SUCCESS)
2283 result = execute_cond_node (cond->right);
2285 else if (cond->type == COND_UNARY)
2287 arg1 = cond_expand_word (cond->left->op, 0);
2290 if (echo_command_at_execute)
2291 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2292 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2293 if (arg1 != nullstr)
2296 else if (cond->type == COND_BINARY)
2298 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2299 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2300 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
2302 arg1 = cond_expand_word (cond->left->op, 0);
2305 arg2 = cond_expand_word (cond->right->op, patmatch);
2309 if (echo_command_at_execute)
2310 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2312 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2314 : EXECUTION_FAILURE;
2315 if (arg1 != nullstr)
2317 if (arg2 != nullstr)
2322 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
2323 jump_to_top_level (DISCARD);
2324 result = EXECUTION_FAILURE;
2328 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2334 execute_cond_command (cond_command)
2335 COND_COM *cond_command;
2339 result = EXECUTION_SUCCESS;
2341 this_command_name = "[[";
2342 /* If we're in a function, update the line number information. */
2343 if (variable_context && interactive_shell)
2344 line_number = cond_command->line - function_line_number;
2346 /* Run the debug trap before each conditional command, but do it after we
2347 update the line number information. */
2348 if (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2352 debug_print_cond_command (cond_command);
2354 last_command_exit_value = result = execute_cond_node (cond_command);
2357 #endif /* COND_COMMAND */
2367 var = bind_variable ("_", arg);
2368 VUNSETATTR (var, att_exported);
2371 /* Execute a null command. Fork a subshell if the command uses pipes or is
2372 to be run asynchronously. This handles all the side effects that are
2373 supposed to take place. */
2375 execute_null_command (redirects, pipe_in, pipe_out, async, old_last_command_subst_pid)
2376 REDIRECT *redirects;
2377 int pipe_in, pipe_out, async;
2378 pid_t old_last_command_subst_pid;
2380 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2382 /* We have a null command, but we really want a subshell to take
2383 care of it. Just fork, do piping and redirections, and exit. */
2384 if (make_child ((char *)NULL, async) == 0)
2386 /* Cancel traps, in trap.c. */
2387 restore_original_signals (); /* XXX */
2389 do_piping (pipe_in, pipe_out);
2391 subshell_environment = SUBSHELL_ASYNC;
2393 if (do_redirections (redirects, 1, 0, 0) == 0)
2394 exit (EXECUTION_SUCCESS);
2396 exit (EXECUTION_FAILURE);
2400 close_pipes (pipe_in, pipe_out);
2401 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2402 unlink_fifo_list ();
2404 return (EXECUTION_SUCCESS);
2409 /* Even if there aren't any command names, pretend to do the
2410 redirections that are specified. The user expects the side
2411 effects to take place. If the redirections fail, then return
2412 failure. Otherwise, if a command substitution took place while
2413 expanding the command or a redirection, return the value of that
2414 substitution. Otherwise, return EXECUTION_SUCCESS. */
2416 if (do_redirections (redirects, 0, 0, 0) != 0)
2417 return (EXECUTION_FAILURE);
2418 else if (old_last_command_subst_pid != last_command_subst_pid)
2419 return (last_command_exit_value);
2421 return (EXECUTION_SUCCESS);
2425 /* This is a hack to suppress word splitting for assignment statements
2426 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2428 fix_assignment_words (words)
2439 for (w = words; w; w = w->next)
2440 if (w->word->flags & W_ASSIGNMENT)
2444 b = builtin_address_internal (words->word->word, 0);
2445 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2448 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP);
2452 /* The meaty part of all the executions. We have to start hacking the
2453 real execution of commands here. Fork a process, set things up,
2454 execute the command. */
2456 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2457 SIMPLE_COM *simple_command;
2458 int pipe_in, pipe_out, async;
2459 struct fd_bitmap *fds_to_close;
2461 WORD_LIST *words, *lastword;
2462 char *command_line, *lastarg, *temp;
2463 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
2464 pid_t old_last_command_subst_pid, old_last_async_pid;
2465 sh_builtin_func_t *builtin;
2468 result = EXECUTION_SUCCESS;
2469 special_builtin_failed = builtin_is_special = 0;
2470 command_line = (char *)0;
2472 /* If we're in a function, update the line number information. */
2473 if (variable_context && interactive_shell)
2474 line_number = simple_command->line - function_line_number;
2476 /* Run the debug trap before each simple command, but do it after we
2477 update the line number information. */
2478 if (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2481 /* Remember what this command line looks like at invocation. */
2482 command_string_index = 0;
2483 print_simple_command (simple_command);
2486 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2488 old_last_command_subst_pid = last_command_subst_pid;
2489 old_last_async_pid = last_asynchronous_pid;
2491 already_forked = dofork = 0;
2493 /* If we're in a pipeline or run in the background, set DOFORK so we
2494 make the child early, before word expansion. This keeps assignment
2495 statements from affecting the parent shell's environment when they
2497 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2499 /* Something like `%2 &' should restart job 2 in the background, not cause
2500 the shell to fork here. */
2501 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2502 simple_command->words && simple_command->words->word &&
2503 simple_command->words->word->word &&
2504 (simple_command->words->word->word[0] == '%'))
2509 /* XXX memory leak if expand_words() error causes a jump_to_top_level */
2510 command_line = savestring (the_printed_command);
2512 /* Do this now, because execute_disk_command will do it anyway in the
2513 vast majority of cases. */
2514 maybe_make_export_env ();
2516 if (make_child (command_line, async) == 0)
2519 simple_command->flags |= CMD_NO_FORK;
2521 subshell_environment = (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2522 ? (SUBSHELL_PIPE|SUBSHELL_FORK)
2523 : (SUBSHELL_ASYNC|SUBSHELL_FORK);
2525 /* We need to do this before piping to handle some really
2526 pathological cases where one of the pipe file descriptors
2529 close_fd_bitmap (fds_to_close);
2531 do_piping (pipe_in, pipe_out);
2532 pipe_in = pipe_out = NO_PIPE;
2534 last_asynchronous_pid = old_last_async_pid;
2538 close_pipes (pipe_in, pipe_out);
2539 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2540 unlink_fifo_list ();
2542 command_line = (char *)NULL; /* don't free this. */
2543 bind_lastarg ((char *)NULL);
2548 /* If we are re-running this as the result of executing the `command'
2549 builtin, do not expand the command words a second time. */
2550 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2552 current_fds_to_close = fds_to_close;
2553 fix_assignment_words (simple_command->words);
2554 words = expand_words (simple_command->words);
2555 current_fds_to_close = (struct fd_bitmap *)NULL;
2558 words = copy_word_list (simple_command->words);
2560 /* It is possible for WORDS not to have anything left in it.
2561 Perhaps all the words consisted of `$foo', and there was
2562 no variable `$foo'. */
2565 result = execute_null_command (simple_command->redirects,
2567 already_forked ? 0 : async,
2568 old_last_command_subst_pid);
2573 bind_lastarg ((char *)NULL);
2574 set_pipestatus_from_exit (result);
2579 lastarg = (char *)NULL;
2581 begin_unwind_frame ("simple-command");
2583 if (echo_command_at_execute)
2584 xtrace_print_word_list (words);
2586 builtin = (sh_builtin_func_t *)NULL;
2587 func = (SHELL_VAR *)NULL;
2588 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2590 /* Posix.2 says special builtins are found before functions. We
2591 don't set builtin_is_special anywhere other than here, because
2592 this path is followed only when the `command' builtin is *not*
2593 being used, and we don't want to exit the shell if a special
2594 builtin executed with `command builtin' fails. `command' is not
2595 a special builtin. */
2596 if (posixly_correct)
2598 builtin = find_special_builtin (words->word->word);
2600 builtin_is_special = 1;
2603 func = find_function (words->word->word);
2606 add_unwind_protect (dispose_words, words);
2609 /* Bind the last word in this command to "$_" after execution. */
2610 for (lastword = words; lastword->next; lastword = lastword->next)
2612 lastarg = lastword->word->word;
2614 #if defined (JOB_CONTROL)
2615 /* Is this command a job control related thing? */
2616 if (words->word->word[0] == '%' && already_forked == 0)
2618 this_command_name = async ? "bg" : "fg";
2619 last_shell_builtin = this_shell_builtin;
2620 this_shell_builtin = builtin_address (this_command_name);
2621 result = (*this_shell_builtin) (words);
2625 /* One other possiblilty. The user may want to resume an existing job.
2626 If they do, find out whether this word is a candidate for a running
2628 if (job_control && already_forked == 0 && async == 0 &&
2629 !first_word_quoted &&
2631 words->word->word[0] &&
2632 !simple_command->redirects &&
2633 pipe_in == NO_PIPE &&
2634 pipe_out == NO_PIPE &&
2635 (temp = get_string_value ("auto_resume")))
2637 int job, jflags, started_status;
2639 jflags = JM_STOPPED|JM_FIRSTMATCH;
2640 if (STREQ (temp, "exact"))
2642 else if (STREQ (temp, "substring"))
2643 jflags |= JM_SUBSTRING;
2645 jflags |= JM_PREFIX;
2646 job = get_job_by_name (words->word->word, jflags);
2649 run_unwind_frame ("simple-command");
2650 this_command_name = "fg";
2651 last_shell_builtin = this_shell_builtin;
2652 this_shell_builtin = builtin_address ("fg");
2654 started_status = start_job (job, 1);
2655 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2658 #endif /* JOB_CONTROL */
2660 /* Remember the name of this command globally. */
2661 this_command_name = words->word->word;
2665 /* This command could be a shell builtin or a user-defined function.
2666 We have already found special builtins by this time, so we do not
2667 set builtin_is_special. If this is a function or builtin, and we
2668 have pipes, then fork a subshell in here. Otherwise, just execute
2669 the command directly. */
2670 if (func == 0 && builtin == 0)
2671 builtin = find_shell_builtin (this_command_name);
2673 last_shell_builtin = this_shell_builtin;
2674 this_shell_builtin = builtin;
2676 if (builtin || func)
2680 /* reset_terminating_signals (); */ /* XXX */
2681 /* Cancel traps, in trap.c. */
2682 restore_original_signals ();
2686 if ((simple_command->flags & CMD_STDIN_REDIR) &&
2687 pipe_in == NO_PIPE &&
2688 (stdin_redirects (simple_command->redirects) == 0))
2689 async_redirect_stdin ();
2690 setup_async_signals ();
2693 execute_subshell_builtin_or_function
2694 (words, simple_command->redirects, builtin, func,
2695 pipe_in, pipe_out, async, fds_to_close,
2696 simple_command->flags);
2700 result = execute_builtin_or_function
2701 (words, builtin, func, simple_command->redirects, fds_to_close,
2702 simple_command->flags);
2705 if (result > EX_SHERRBASE)
2707 result = builtin_status (result);
2708 if (builtin_is_special)
2709 special_builtin_failed = 1;
2711 /* In POSIX mode, if there are assignment statements preceding
2712 a special builtin, they persist after the builtin
2714 if (posixly_correct && builtin_is_special && temporary_env)
2715 merge_temporary_env ();
2719 if (result == EX_USAGE)
2720 result = EX_BADUSAGE;
2721 else if (result > EX_SHERRBASE)
2722 result = EXECUTION_FAILURE;
2725 set_pipestatus_from_exit (result);
2731 if (command_line == 0)
2732 command_line = savestring (the_printed_command);
2734 execute_disk_command (words, simple_command->redirects, command_line,
2735 pipe_in, pipe_out, async, fds_to_close,
2736 simple_command->flags);
2739 bind_lastarg (lastarg);
2740 FREE (command_line);
2741 run_unwind_frame ("simple-command");
2745 /* Translate the special builtin exit statuses. We don't really need a
2746 function for this; it's a placeholder for future work. */
2748 builtin_status (result)
2762 r = EXECUTION_FAILURE;
2765 r = EXECUTION_SUCCESS;
2772 execute_builtin (builtin, words, flags, subshell)
2773 sh_builtin_func_t *builtin;
2775 int flags, subshell;
2777 int old_e_flag, result, eval_unwind;
2780 old_e_flag = exit_immediately_on_error;
2781 /* The eval builtin calls parse_and_execute, which does not know about
2782 the setting of flags, and always calls the execution functions with
2783 flags that will exit the shell on an error if -e is set. If the
2784 eval builtin is being called, and we're supposed to ignore the exit
2785 value of the command, we turn the -e flag off ourselves, then
2786 restore it when the command completes. */
2787 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
2789 begin_unwind_frame ("eval_builtin");
2790 unwind_protect_int (exit_immediately_on_error);
2791 exit_immediately_on_error = 0;
2797 /* The temporary environment for a builtin is supposed to apply to
2798 all commands executed by that builtin. Currently, this is a
2799 problem only with the `source' and `eval' builtins. */
2800 isbltinenv = (builtin == source_builtin || builtin == eval_builtin);
2804 begin_unwind_frame ("builtin_env");
2808 push_scope (VC_BLTNENV, temporary_env);
2810 add_unwind_protect (pop_scope, "1");
2811 temporary_env = (HASH_TABLE *)NULL;
2815 /* `return' does a longjmp() back to a saved environment in execute_function.
2816 If a variable assignment list preceded the command, and the shell is
2817 running in POSIX mode, we need to merge that into the shell_variables
2818 table, since `return' is a POSIX special builtin. */
2819 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
2821 begin_unwind_frame ("return_temp_env");
2822 add_unwind_protect (merge_temporary_env, (char *)NULL);
2825 result = ((*builtin) (words->next));
2827 /* This shouldn't happen, but in case `return' comes back instead of
2828 longjmp'ing, we need to unwind. */
2829 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
2830 discard_unwind_frame ("return_temp_env");
2832 if (subshell == 0 && isbltinenv)
2833 run_unwind_frame ("builtin_env");
2837 exit_immediately_on_error += old_e_flag;
2838 discard_unwind_frame ("eval_builtin");
2845 execute_function (var, words, flags, fds_to_close, async, subshell)
2849 struct fd_bitmap *fds_to_close;
2850 int async, subshell;
2852 int return_val, result;
2854 char *debug_trap, *error_trap;
2858 tc = (COMMAND *)copy_command (function_cell (var));
2859 if (tc && (flags & CMD_IGNORE_RETURN))
2860 tc->flags |= CMD_IGNORE_RETURN;
2864 begin_unwind_frame ("function_calling");
2865 push_context (var->name, subshell, temporary_env);
2866 add_unwind_protect (pop_context, (char *)NULL);
2867 unwind_protect_int (line_number);
2868 unwind_protect_int (return_catch_flag);
2869 unwind_protect_jmp_buf (return_catch);
2870 add_unwind_protect (dispose_command, (char *)tc);
2871 unwind_protect_pointer (this_shell_function);
2872 unwind_protect_int (loop_level);
2875 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
2877 temporary_env = (HASH_TABLE *)NULL;
2879 this_shell_function = var;
2880 make_funcname_visible (1);
2882 debug_trap = TRAP_STRING(DEBUG_TRAP);
2883 error_trap = TRAP_STRING(ERROR_TRAP);
2885 /* The order of the unwind protects for debug_trap and error_trap is
2886 important here! unwind-protect commands are run in reverse order
2887 of registration. If this causes problems, take out the xfree
2888 unwind-protect calls and live with the small memory leak. */
2889 if (debug_trap && (trace_p (var) == 0))
2893 debug_trap = savestring (debug_trap);
2894 add_unwind_protect (xfree, debug_trap);
2895 add_unwind_protect (set_debug_trap, debug_trap);
2897 restore_default_signal (DEBUG_TRAP);
2904 error_trap = savestring (error_trap);
2905 add_unwind_protect (xfree, error_trap);
2906 add_unwind_protect (set_error_trap, error_trap);
2908 restore_default_signal (ERROR_TRAP);
2911 /* The temporary environment for a function is supposed to apply to
2912 all commands executed within the function body. */
2914 remember_args (words->next, 1);
2916 /* Number of the line on which the function body starts. */
2917 if (interactive_shell)
2918 line_number = function_line_number = tc->line;
2922 #if defined (JOB_CONTROL)
2923 stop_pipeline (async, (COMMAND *)NULL);
2925 fc = (tc->type == cm_group) ? tc->value.Group->command : tc;
2927 if (fc && (flags & CMD_IGNORE_RETURN))
2928 fc->flags |= CMD_IGNORE_RETURN;
2933 return_catch_flag++;
2934 return_val = setjmp (return_catch);
2937 result = return_catch_value;
2939 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
2942 run_unwind_frame ("function_calling");
2944 if (variable_context == 0 || this_shell_function == 0)
2945 make_funcname_visible (0);
2950 /* A convenience routine for use by other parts of the shell to execute
2951 a particular shell function. */
2953 execute_shell_function (var, words)
2958 struct fd_bitmap *bitmap;
2960 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
2961 begin_unwind_frame ("execute-shell-function");
2962 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
2964 ret = execute_function (var, words, 0, bitmap, 0, 0);
2966 dispose_fd_bitmap (bitmap);
2967 discard_unwind_frame ("execute-shell-function");
2972 /* Execute a shell builtin or function in a subshell environment. This
2973 routine does not return; it only calls exit(). If BUILTIN is non-null,
2974 it points to a function to call to execute a shell builtin; otherwise
2975 VAR points at the body of a function to execute. WORDS is the arguments
2976 to the command, REDIRECTS specifies redirections to perform before the
2977 command is executed. */
2979 execute_subshell_builtin_or_function (words, redirects, builtin, var,
2980 pipe_in, pipe_out, async, fds_to_close,
2983 REDIRECT *redirects;
2984 sh_builtin_func_t *builtin;
2986 int pipe_in, pipe_out, async;
2987 struct fd_bitmap *fds_to_close;
2991 #if defined (JOB_CONTROL)
2994 jobs_hack = (builtin == jobs_builtin) &&
2995 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
2998 /* A subshell is neither a login shell nor interactive. */
2999 login_shell = interactive = 0;
3001 subshell_environment = SUBSHELL_ASYNC;
3003 maybe_make_export_env (); /* XXX - is this needed? */
3005 #if defined (JOB_CONTROL)
3006 /* Eradicate all traces of job control after we fork the subshell, so
3007 all jobs begun by this subshell are in the same process group as
3008 the shell itself. */
3010 /* Allow the output of `jobs' to be piped. */
3012 kill_current_pipeline ();
3014 without_job_control ();
3016 set_sigchld_handler ();
3017 #endif /* JOB_CONTROL */
3019 set_sigint_handler ();
3022 close_fd_bitmap (fds_to_close);
3024 do_piping (pipe_in, pipe_out);
3026 if (do_redirections (redirects, 1, 0, 0) != 0)
3027 exit (EXECUTION_FAILURE);
3031 /* Give builtins a place to jump back to on failure,
3032 so we don't go back up to main(). */
3033 result = setjmp (top_level);
3035 if (result == EXITPROG)
3036 exit (last_command_exit_value);
3038 exit (EXECUTION_FAILURE);
3041 r = execute_builtin (builtin, words, flags, 1);
3048 exit (execute_function (var, words, flags, fds_to_close, async, 1));
3051 /* Execute a builtin or function in the current shell context. If BUILTIN
3052 is non-null, it is the builtin command to execute, otherwise VAR points
3053 to the body of a function. WORDS are the command's arguments, REDIRECTS
3054 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
3055 file descriptors to close.
3057 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
3058 not undone before this function returns. */
3060 execute_builtin_or_function (words, builtin, var, redirects,
3061 fds_to_close, flags)
3063 sh_builtin_func_t *builtin;
3065 REDIRECT *redirects;
3066 struct fd_bitmap *fds_to_close;
3070 REDIRECT *saved_undo_list;
3071 sh_builtin_func_t *saved_this_shell_builtin;
3073 if (do_redirections (redirects, 1, 1, 0) != 0)
3075 cleanup_redirects (redirection_undo_list);
3076 redirection_undo_list = (REDIRECT *)NULL;
3077 dispose_exec_redirects ();
3078 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
3081 saved_this_shell_builtin = this_shell_builtin;
3082 saved_undo_list = redirection_undo_list;
3084 /* Calling the "exec" builtin changes redirections forever. */
3085 if (builtin == exec_builtin)
3087 dispose_redirects (saved_undo_list);
3088 saved_undo_list = exec_redirection_undo_list;
3089 exec_redirection_undo_list = (REDIRECT *)NULL;
3092 dispose_exec_redirects ();
3094 if (saved_undo_list)
3096 begin_unwind_frame ("saved redirects");
3097 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
3100 redirection_undo_list = (REDIRECT *)NULL;
3103 result = execute_builtin (builtin, words, flags, 0);
3105 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3107 /* If we are executing the `command' builtin, but this_shell_builtin is
3108 set to `exec_builtin', we know that we have something like
3109 `command exec [redirection]', since otherwise `exec' would have
3110 overwritten the shell and we wouldn't get here. In this case, we
3111 want to behave as if the `command' builtin had not been specified
3112 and preserve the redirections. */
3113 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
3115 if (saved_undo_list)
3116 dispose_redirects (saved_undo_list);
3117 redirection_undo_list = exec_redirection_undo_list;
3118 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
3119 discard_unwind_frame ("saved_redirects");
3122 if (saved_undo_list)
3124 redirection_undo_list = saved_undo_list;
3125 discard_unwind_frame ("saved redirects");
3128 if (redirection_undo_list)
3130 cleanup_redirects (redirection_undo_list);
3131 redirection_undo_list = (REDIRECT *)NULL;
3138 setup_async_signals ()
3140 #if defined (__BEOS__)
3141 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3144 #if defined (JOB_CONTROL)
3145 if (job_control == 0)
3148 set_signal_handler (SIGINT, SIG_IGN);
3149 set_signal_ignored (SIGINT);
3150 set_signal_handler (SIGQUIT, SIG_IGN);
3151 set_signal_ignored (SIGQUIT);
3155 /* Execute a simple command that is hopefully defined in a disk file
3160 3) look up the command
3163 6) If the execve failed, see if the file has executable mode set.
3164 If so, and it isn't a directory, then execute its contents as
3167 Note that the filename hashing stuff has to take place up here,
3168 in the parent. This is probably why the Bourne style shells
3169 don't handle it, since that would require them to go through
3170 this gnarly hair, for no good reason. */
3172 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
3173 async, fds_to_close, cmdflags)
3175 REDIRECT *redirects;
3177 int pipe_in, pipe_out, async;
3178 struct fd_bitmap *fds_to_close;
3181 char *pathname, *command, **args;
3185 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
3186 pathname = words->word->word;
3188 #if defined (RESTRICTED_SHELL)
3189 if (restricted && xstrchr (pathname, '/'))
3191 internal_error ("%s: restricted: cannot specify `/' in command names",
3193 last_command_exit_value = EXECUTION_FAILURE;
3196 #endif /* RESTRICTED_SHELL */
3198 command = search_for_command (pathname);
3202 maybe_make_export_env ();
3203 put_command_name_into_env (command);
3206 /* We have to make the child before we check for the non-existence
3207 of COMMAND, since we want the error messages to be redirected. */
3208 /* If we can get away without forking and there are no pipes to deal with,
3209 don't bother to fork, just directly exec the command. */
3210 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3213 pid = make_child (savestring (command_line), async);
3217 int old_interactive;
3220 /* This has been disabled for the time being. */
3221 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3222 if (posixly_correct == 0)
3223 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
3227 /* Cancel traps, in trap.c. */
3228 restore_original_signals ();
3230 /* restore_original_signals may have undone the work done
3231 by make_child to ensure that SIGINT and SIGQUIT are ignored
3232 in asynchronous children. */
3235 if ((cmdflags & CMD_STDIN_REDIR) &&
3236 pipe_in == NO_PIPE &&
3237 (stdin_redirects (redirects) == 0))
3238 async_redirect_stdin ();
3239 setup_async_signals ();
3242 /* This functionality is now provided by close-on-exec of the
3243 file descriptors manipulated by redirection and piping.
3244 Some file descriptors still need to be closed in all children
3245 because of the way bash does pipes; fds_to_close is a
3246 bitmap of all such file descriptors. */
3248 close_fd_bitmap (fds_to_close);
3250 do_piping (pipe_in, pipe_out);
3252 old_interactive = interactive;
3256 subshell_environment = SUBSHELL_FORK;
3258 if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
3260 #if defined (PROCESS_SUBSTITUTION)
3261 /* Try to remove named pipes that may have been created as the
3262 result of redirections. */
3263 unlink_fifo_list ();
3264 #endif /* PROCESS_SUBSTITUTION */
3265 exit (EXECUTION_FAILURE);
3269 interactive = old_interactive;
3273 internal_error ("%s: command not found", pathname);
3274 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3277 /* Execve expects the command name to be in args[0]. So we
3278 leave it there, in the same format that the user used to
3280 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
3281 exit (shell_execve (command, args, export_env));
3285 /* Make sure that the pipes are closed in the parent. */
3286 close_pipes (pipe_in, pipe_out);
3287 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3288 unlink_fifo_list ();
3294 /* CPP defines to decide whether a particular index into the #! line
3295 corresponds to a valid interpreter name or argument character, or
3296 whitespace. The MSDOS define is to allow \r to be treated the same
3299 #if !defined (MSDOS)
3300 # define STRINGCHAR(ind) \
3301 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
3302 # define WHITECHAR(ind) \
3303 (ind < sample_len && whitespace (sample[ind]))
3305 # define STRINGCHAR(ind) \
3306 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
3307 # define WHITECHAR(ind) \
3308 (ind < sample_len && whitespace (sample[ind]))
3312 getinterp (sample, sample_len, endp)
3314 int sample_len, *endp;
3320 /* Find the name of the interpreter to exec. */
3321 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
3324 for (start = i; STRINGCHAR(i); i++)
3327 execname = substring (sample, start, i);
3334 #if !defined (HAVE_HASH_BANG_EXEC)
3335 /* If the operating system on which we're running does not handle
3336 the #! executable format, then help out. SAMPLE is the text read
3337 from the file, SAMPLE_LEN characters. COMMAND is the name of
3338 the script; it and ARGS, the arguments given by the user, will
3339 become arguments to the specified interpreter. ENV is the environment
3340 to pass to the interpreter.
3342 The word immediately following the #! is the interpreter to execute.
3343 A single argument to the interpreter is allowed. */
3346 execute_shell_script (sample, sample_len, command, args, env)
3352 char *execname, *firstarg;
3353 int i, start, size_increment, larry;
3355 /* Find the name of the interpreter to exec. */
3356 execname = getinterp (sample, sample_len, &i);
3359 /* Now the argument, if any. */
3360 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
3363 /* If there is more text on the line, then it is an argument for the
3368 for (start = i; STRINGCHAR(i); i++)
3370 firstarg = substring ((char *)sample, start, i);
3374 larry = strvec_len (args) + size_increment;
3375 args = strvec_resize (args, larry + 1);
3377 for (i = larry - 1; i; i--)
3378 args[i] = args[i - size_increment];
3389 args[larry] = (char *)NULL;
3391 return (shell_execve (execname, args, env));
3396 #endif /* !HAVE_HASH_BANG_EXEC */
3399 initialize_subshell ()
3402 /* Forget about any aliases that we knew of. We are in a subshell. */
3403 delete_all_aliases ();
3406 #if defined (HISTORY)
3407 /* Forget about the history lines we have read. This is a non-interactive
3409 history_lines_this_session = 0;
3412 #if defined (JOB_CONTROL)
3413 /* Forget about the way job control was working. We are in a subshell. */
3414 without_job_control ();
3415 set_sigchld_handler ();
3416 #endif /* JOB_CONTROL */
3418 /* Reset the values of the shell flags and options. */
3419 reset_shell_flags ();
3420 reset_shell_options ();
3421 reset_shopt_options ();
3423 /* Zero out builtin_env, since this could be a shell script run from a
3424 sourced file with a temporary environment supplied to the `source/.'
3425 builtin. Such variables are not supposed to be exported (empirical
3426 testing with sh and ksh). Just throw it away; don't worry about a
3428 if (vc_isbltnenv (shell_variables))
3429 shell_variables = shell_variables->down;
3431 clear_unwind_protect_list (0);
3433 /* We're no longer inside a shell function. */
3434 variable_context = return_catch_flag = 0;
3436 /* If we're not interactive, close the file descriptor from which we're
3437 reading the current shell script. */
3438 if (interactive_shell == 0)
3439 unset_bash_input (1);
3442 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3443 # define SETOSTYPE(x) __setostype(x)
3445 # define SETOSTYPE(x)
3448 #define READ_SAMPLE_BUF(file, buf, len) \
3451 fd = open(file, O_RDONLY); \
3454 len = read (fd, buf, 80); \
3462 /* Call execve (), handling interpreting shell scripts, and handling
3465 shell_execve (command, args, env)
3474 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3475 execve (command, args, env);
3476 i = errno; /* error from execve() */
3479 /* If we get to this point, then start checking out the file.
3480 Maybe it is something we can hack ourselves. */
3483 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3484 internal_error ("%s: is a directory", command);
3485 else if (executable_file (command) == 0)
3488 file_error (command);
3492 /* The file has the execute bits set, but the kernel refuses to
3493 run it for some reason. See why. */
3494 #if defined (HAVE_HASH_BANG_EXEC)
3495 READ_SAMPLE_BUF (command, sample, sample_len);
3496 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3500 interp = getinterp (sample, sample_len, (int *)NULL);
3502 sys_error ("%s: %s: bad interpreter", command, interp ? interp : "");
3508 file_error (command);
3510 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3513 /* This file is executable.
3514 If it begins with #!, then help out people with losing operating
3515 systems. Otherwise, check to see if it is a binary file by seeing
3516 if the contents of the first line (or up to 80 characters) are in the
3517 ASCII set. If it's a text file, execute the contents as shell commands,
3518 otherwise return 126 (EX_BINARY_FILE). */
3519 READ_SAMPLE_BUF (command, sample, sample_len);
3521 if (sample_len == 0)
3522 return (EXECUTION_SUCCESS);
3524 /* Is this supposed to be an executable script?
3525 If so, the format of the line is "#! interpreter [argument]".
3526 A single argument is allowed. The BSD kernel restricts
3527 the length of the entire line to 32 characters (32 bytes
3528 being the size of the BSD exec header), but we allow 80
3532 #if !defined (HAVE_HASH_BANG_EXEC)
3533 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3534 return (execute_shell_script (sample, sample_len, command, args, env));
3537 if (check_binary_file (sample, sample_len))
3539 internal_error ("%s: cannot execute binary file", command);
3540 return (EX_BINARY_FILE);
3544 /* We have committed to attempting to execute the contents of this file
3545 as shell commands. */
3547 initialize_subshell ();
3549 set_sigint_handler ();
3551 /* Insert the name of this shell into the argument list. */
3552 larray = strvec_len (args) + 1;
3553 args = strvec_resize (args, larray + 1);
3555 for (i = larray - 1; i; i--)
3556 args[i] = args[i - 1];
3558 args[0] = shell_name;
3560 args[larray] = (char *)NULL;
3562 if (args[0][0] == '-')
3565 #if defined (RESTRICTED_SHELL)
3567 change_flag ('r', FLAG_OFF);
3572 /* Can't free subshell_argv[0]; that is shell_name. */
3573 for (i = 1; i < subshell_argc; i++)
3574 free (subshell_argv[i]);
3575 free (subshell_argv);
3578 dispose_command (currently_executing_command); /* XXX */
3579 currently_executing_command = (COMMAND *)NULL;
3581 subshell_argc = larray;
3582 subshell_argv = args;
3583 subshell_envp = env;
3585 unbind_args (); /* remove the positional parameters */
3587 longjmp (subshell_top_level, 1);
3592 execute_intern_function (name, function)
3598 if (check_identifier (name, posixly_correct) == 0)
3600 if (posixly_correct && interactive_shell == 0)
3602 last_command_exit_value = EX_USAGE;
3603 jump_to_top_level (EXITPROG);
3605 return (EXECUTION_FAILURE);
3608 var = find_function (name->word);
3609 if (var && (readonly_p (var) || noassign_p (var)))
3611 if (readonly_p (var))
3612 internal_error ("%s: readonly function", var->name);
3613 return (EXECUTION_FAILURE);
3616 bind_function (name->word, function);
3617 return (EXECUTION_SUCCESS);
3620 #if defined (INCLUDE_UNUSED)
3621 #if defined (PROCESS_SUBSTITUTION)
3625 register int i, fd_table_size;
3627 fd_table_size = getdtablesize ();
3628 if (fd_table_size > 256) /* clamp to a reasonable value */
3629 fd_table_size = 256;
3631 for (i = 3; i < fd_table_size; i++)
3634 #endif /* PROCESS_SUBSTITUTION */
3638 close_pipes (in, out)
3647 /* Redirect input and output to be from and to the specified pipes.
3648 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3650 do_piping (pipe_in, pipe_out)
3651 int pipe_in, pipe_out;
3653 if (pipe_in != NO_PIPE)
3655 if (dup2 (pipe_in, 0) < 0)
3656 sys_error ("cannot duplicate fd %d to fd 0", pipe_in);
3660 if (pipe_out != NO_PIPE)
3662 if (pipe_out != REDIRECT_BOTH)
3664 if (dup2 (pipe_out, 1) < 0)
3665 sys_error ("cannot duplicate fd %d to fd 1", pipe_out);
3666 if (pipe_out == 0 || pipe_out > 1)
3671 if (dup2 (1, 2) < 0)
3672 sys_error ("cannot duplicate fd 1 to fd 2");