1 /* execute_command.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987-2003 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"
29 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_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>
64 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
69 #include "execute_cmd.h"
76 #if defined (COND_COMMAND)
80 #include "builtins/common.h"
81 #include "builtins/builtext.h" /* list of builtins */
83 #include <glob/strmatch.h>
84 #include <tilde/tilde.h>
86 #if defined (BUFFERED_INPUT)
95 # include "bashhist.h"
98 extern int posixly_correct;
99 extern int breaking, continuing, loop_level;
100 extern int expand_aliases;
101 extern int parse_and_execute_level, running_trap;
102 extern int command_string_index, line_number;
103 extern int dot_found_in_search;
104 extern int already_making_children;
105 extern int tempenv_assign_error;
106 extern char *the_printed_command, *shell_name;
107 extern pid_t last_command_subst_pid;
108 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
109 extern char **subshell_argv, **subshell_envp;
110 extern int subshell_argc;
112 extern char *glob_argv_flags;
115 extern int close __P((int));
117 /* Static functions defined and used in this file. */
118 static void close_pipes __P((int, int));
119 static void do_piping __P((int, int));
120 static void bind_lastarg __P((char *));
121 static int shell_control_structure __P((enum command_type));
122 static void cleanup_redirects __P((REDIRECT *));
124 #if defined (JOB_CONTROL)
125 static int restore_signal_mask __P((sigset_t *));
128 static void async_redirect_stdin __P((void));
130 static int builtin_status __P((int));
132 static int execute_for_command __P((FOR_COM *));
133 #if defined (SELECT_COMMAND)
134 static int print_index_and_element __P((int, int, WORD_LIST *));
135 static void indent __P((int, int));
136 static void print_select_list __P((WORD_LIST *, int, int, int));
137 static char *select_query __P((WORD_LIST *, int, char *, int));
138 static int execute_select_command __P((SELECT_COM *));
140 #if defined (DPAREN_ARITHMETIC)
141 static int execute_arith_command __P((ARITH_COM *));
143 #if defined (COND_COMMAND)
144 static int execute_cond_node __P((COND_COM *));
145 static int execute_cond_command __P((COND_COM *));
147 #if defined (COMMAND_TIMING)
148 static int mkfmt __P((char *, int, int, time_t, int));
149 static void print_formatted_time __P((FILE *, char *,
150 time_t, int, time_t, int,
152 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
154 #if defined (ARITH_FOR_COMMAND)
155 static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
156 static int execute_arith_for_command __P((ARITH_FOR_COM *));
158 static int execute_case_command __P((CASE_COM *));
159 static int execute_while_command __P((WHILE_COM *));
160 static int execute_until_command __P((WHILE_COM *));
161 static int execute_while_or_until __P((WHILE_COM *, int));
162 static int execute_if_command __P((IF_COM *));
163 static int execute_null_command __P((REDIRECT *, int, int, int, pid_t));
164 static void fix_assignment_words __P((WORD_LIST *));
165 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
166 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
167 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
168 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
170 REDIRECT *, struct fd_bitmap *, int));
171 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
177 static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
178 int, int, int, struct fd_bitmap *, int));
180 static char *getinterp __P((char *, int, int *));
181 static void initialize_subshell __P((void));
182 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
184 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
186 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
188 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
190 /* The line number that the currently executing function starts on. */
191 static int function_line_number;
193 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
194 so that reader_loop can set it to zero before executing a command. */
197 /* The name of the command that is currently being executed.
198 `test' needs this, for example. */
199 char *this_command_name;
201 /* The printed representation of the currently-executing command (same as
202 the_printed_command), except when a trap is being executed. Useful for
203 a debugger to know where exactly the program is currently executing. */
204 char *the_printed_command_except_trap;
206 static COMMAND *currently_executing_command;
208 struct stat SB; /* used for debugging */
210 static int special_builtin_failed;
212 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
213 number containing the function name. Used by executing_line_number to
214 report the correct line number. Kind of a hack. */
215 static int showing_function_line;
217 /* For catching RETURN in a function. */
218 int return_catch_flag;
219 int return_catch_value;
220 procenv_t return_catch;
222 /* The value returned by the last synchronous command. */
223 int last_command_exit_value;
225 /* Whether or not the last command (corresponding to last_command_exit_value)
226 was terminated by a signal, and, if so, which one. */
227 int last_command_exit_signal;
229 /* The list of redirections to perform which will undo the redirections
230 that I made in the shell. */
231 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
233 /* The list of redirections to perform which will undo the internal
234 redirections performed by the `exec' builtin. These are redirections
235 that must be undone even when exec discards redirection_undo_list. */
236 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
238 /* Non-zero if we have just forked and are currently running in a subshell
240 int subshell_environment;
242 /* Count of nested subshells, like SHLVL. Available via $BASH_SUBSHELL */
243 int subshell_level = 0;
245 /* Currently-executing shell function. */
246 SHELL_VAR *this_shell_function;
248 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
250 #define FD_BITMAP_DEFAULT_SIZE 32
252 /* Functions to allocate and deallocate the structures used to pass
253 information from the shell to its children about file descriptors
259 struct fd_bitmap *ret;
261 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
267 ret->bitmap = (char *)xmalloc (size);
268 memset (ret->bitmap, '\0', size);
271 ret->bitmap = (char *)NULL;
276 dispose_fd_bitmap (fdbp)
277 struct fd_bitmap *fdbp;
284 close_fd_bitmap (fdbp)
285 struct fd_bitmap *fdbp;
291 for (i = 0; i < fdbp->size; i++)
300 /* Return the line number of the currently executing command. */
302 executing_line_number ()
304 if (executing && showing_function_line == 0 &&
305 (variable_context == 0 || interactive_shell == 0) &&
306 currently_executing_command)
308 #if defined (COND_COMMAND)
309 if (currently_executing_command->type == cm_cond)
310 return currently_executing_command->value.Cond->line;
312 #if defined (DPAREN_ARITHMETIC)
313 else if (currently_executing_command->type == cm_arith)
314 return currently_executing_command->value.Arith->line;
316 #if defined (ARITH_FOR_COMMAND)
317 else if (currently_executing_command->type == cm_arith_for)
318 return currently_executing_command->value.ArithFor->line;
327 /* Execute the command passed in COMMAND. COMMAND is exactly what
328 read_command () places into GLOBAL_COMMAND. See "command.h" for the
329 details of the command structure.
331 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
332 return values. Executing a command with nothing in it returns
333 EXECUTION_SUCCESS. */
335 execute_command (command)
338 struct fd_bitmap *bitmap;
341 current_fds_to_close = (struct fd_bitmap *)NULL;
342 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
343 begin_unwind_frame ("execute-command");
344 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
346 /* Just do the command, but not asynchronously. */
347 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
349 dispose_fd_bitmap (bitmap);
350 discard_unwind_frame ("execute-command");
352 #if defined (PROCESS_SUBSTITUTION)
353 /* don't unlink fifos if we're in a shell function; wait until the function
355 if (variable_context == 0)
357 #endif /* PROCESS_SUBSTITUTION */
362 /* Return 1 if TYPE is a shell control structure type. */
364 shell_control_structure (type)
365 enum command_type type;
370 #if defined (ARITH_FOR_COMMAND)
373 #if defined (SELECT_COMMAND)
376 #if defined (DPAREN_ARITHMETIC)
379 #if defined (COND_COMMAND)
394 /* A function to use to unwind_protect the redirection undo list
397 cleanup_redirects (list)
400 do_redirections (list, RX_ACTIVE);
401 dispose_redirects (list);
405 /* Function to unwind_protect the redirections for functions and builtins. */
407 cleanup_func_redirects (list)
410 do_redirections (list, RX_ACTIVE);
415 dispose_exec_redirects ()
417 if (exec_redirection_undo_list)
419 dispose_redirects (exec_redirection_undo_list);
420 exec_redirection_undo_list = (REDIRECT *)NULL;
424 #if defined (JOB_CONTROL)
425 /* A function to restore the signal mask to its proper value when the shell
426 is interrupted or errors occur while creating a pipeline. */
428 restore_signal_mask (set)
431 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
433 #endif /* JOB_CONTROL */
436 /* A debugging function that can be called from gdb, for instance. */
441 int f, fd_table_size;
443 fd_table_size = getdtablesize ();
445 fprintf (stderr, "pid %ld open files:", (long)getpid ());
446 for (i = 3; i < fd_table_size; i++)
448 if ((f = fcntl (i, F_GETFD, 0)) != -1)
449 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
451 fprintf (stderr, "\n");
456 async_redirect_stdin ()
460 fd = open ("/dev/null", O_RDONLY);
467 internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
470 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
472 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
473 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
474 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
475 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
476 from and where it goes. They can have the value of NO_PIPE, which means
478 FDS_TO_CLOSE is a list of file descriptors to close once the child has
479 been forked. This list often contains the unusable sides of pipes, etc.
481 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
482 return values. Executing a command with nothing in it returns
483 EXECUTION_SUCCESS. */
485 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
489 int pipe_in, pipe_out;
490 struct fd_bitmap *fds_to_close;
492 int exec_result, invert, ignore_return, was_error_trap;
493 REDIRECT *my_undo_list, *exec_undo_list;
494 volatile pid_t last_pid;
495 volatile int save_line_number;
497 if (command == 0 || breaking || continuing || read_but_dont_execute)
498 return (EXECUTION_SUCCESS);
500 run_pending_traps ();
503 if (running_trap == 0)
505 currently_executing_command = command;
507 invert = (command->flags & CMD_INVERT_RETURN) != 0;
509 /* If we're inverting the return value and `set -e' has been executed,
510 we don't want a failing command to inadvertently cause the shell
512 if (exit_immediately_on_error && invert) /* XXX */
513 command->flags |= CMD_IGNORE_RETURN; /* XXX */
515 exec_result = EXECUTION_SUCCESS;
517 /* If a command was being explicitly run in a subshell, or if it is
518 a shell control-structure, and it has a pipe, then we do the command
520 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
521 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
523 if (command->type == cm_subshell ||
524 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
525 (shell_control_structure (command->type) &&
526 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
530 /* Fork a subshell, turn off the subshell bit, turn off job
531 control and call execute_command () on the command again. */
532 paren_pid = make_child (savestring (make_command_string (command)),
535 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
539 close_pipes (pipe_in, pipe_out);
541 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
544 /* If we are part of a pipeline, and not the end of the pipeline,
545 then we should simply return and let the last command in the
546 pipe be waited for. If we are not in a pipeline, or are the
547 last command in the pipeline, then we wait for the subshell
548 and return its exit status as usual. */
549 if (pipe_out != NO_PIPE)
550 return (EXECUTION_SUCCESS);
552 stop_pipeline (asynchronous, (COMMAND *)NULL);
554 if (asynchronous == 0)
556 last_command_exit_value = wait_for (paren_pid);
558 /* If we have to, invert the return value. */
560 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
562 : EXECUTION_SUCCESS);
564 exec_result = last_command_exit_value;
566 return (last_command_exit_value = exec_result);
570 DESCRIBE_PID (paren_pid);
572 run_pending_traps ();
574 return (EXECUTION_SUCCESS);
579 #if defined (COMMAND_TIMING)
580 if (command->flags & CMD_TIME_PIPELINE)
584 command->flags |= CMD_FORCE_SUBSHELL;
585 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
589 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
591 if (running_trap == 0)
593 currently_executing_command = (COMMAND *)NULL;
595 return (exec_result);
597 #endif /* COMMAND_TIMING */
599 if (shell_control_structure (command->type) && command->redirects)
600 stdin_redir = stdin_redirects (command->redirects);
602 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
604 if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
606 cleanup_redirects (redirection_undo_list);
607 redirection_undo_list = (REDIRECT *)NULL;
608 dispose_exec_redirects ();
609 return (EXECUTION_FAILURE);
612 if (redirection_undo_list)
614 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
615 dispose_redirects (redirection_undo_list);
616 redirection_undo_list = (REDIRECT *)NULL;
619 my_undo_list = (REDIRECT *)NULL;
621 if (exec_redirection_undo_list)
623 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
624 dispose_redirects (exec_redirection_undo_list);
625 exec_redirection_undo_list = (REDIRECT *)NULL;
628 exec_undo_list = (REDIRECT *)NULL;
630 if (my_undo_list || exec_undo_list)
631 begin_unwind_frame ("loop_redirections");
634 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
637 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
639 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
643 switch (command->type)
647 save_line_number = line_number;
648 /* We can't rely on variables retaining their values across a
649 call to execute_simple_command if a longjmp occurs as the
650 result of a `return' builtin. This is true for sure with gcc. */
651 last_pid = last_made_pid;
652 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
654 if (ignore_return && command->value.Simple)
655 command->value.Simple->flags |= CMD_IGNORE_RETURN;
656 if (command->flags & CMD_STDIN_REDIR)
657 command->value.Simple->flags |= CMD_STDIN_REDIR;
659 line_number = command->value.Simple->line;
661 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
662 asynchronous, fds_to_close);
663 line_number = save_line_number;
665 /* The temporary environment should be used for only the simple
666 command immediately following its definition. */
667 dispose_used_env_vars ();
669 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
670 /* Reclaim memory allocated with alloca () on machines which
671 may be using the alloca emulation code. */
673 #endif /* (ultrix && mips) || C_ALLOCA */
675 /* If we forked to do the command, then we must wait_for ()
678 /* XXX - this is something to watch out for if there are problems
679 when the shell is compiled without job control. */
680 if (already_making_children && pipe_out == NO_PIPE &&
681 last_pid != last_made_pid)
683 stop_pipeline (asynchronous, (COMMAND *)NULL);
687 DESCRIBE_PID (last_made_pid);
690 #if !defined (JOB_CONTROL)
691 /* Do not wait for asynchronous processes started from
693 if (last_made_pid != last_asynchronous_pid)
695 /* When executing a shell function that executes other
696 commands, this causes the last simple command in
697 the function to be waited for twice. This also causes
698 subshells forked to execute builtin commands (e.g., in
699 pipelines) to be waited for twice. */
700 exec_result = wait_for (last_made_pid);
701 #if defined (RECYCLES_PIDS)
702 /* LynxOS, for one, recycles pids very quickly -- so quickly
703 that a new process may have the same pid as the last one
704 created. This has been reported to fix the problem on that
705 OS, and a similar problem on Cygwin. */
706 if (exec_result == 0)
707 last_made_pid = NO_PID;
712 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
714 last_command_exit_value = exec_result;
718 if (ignore_return == 0 && invert == 0 &&
719 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
720 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
722 last_command_exit_value = exec_result;
723 run_pending_traps ();
724 jump_to_top_level (ERREXIT);
731 command->value.For->flags |= CMD_IGNORE_RETURN;
732 exec_result = execute_for_command (command->value.For);
735 #if defined (ARITH_FOR_COMMAND)
738 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
739 exec_result = execute_arith_for_command (command->value.ArithFor);
743 #if defined (SELECT_COMMAND)
746 command->value.Select->flags |= CMD_IGNORE_RETURN;
747 exec_result = execute_select_command (command->value.Select);
753 command->value.Case->flags |= CMD_IGNORE_RETURN;
754 exec_result = execute_case_command (command->value.Case);
759 command->value.While->flags |= CMD_IGNORE_RETURN;
760 exec_result = execute_while_command (command->value.While);
765 command->value.While->flags |= CMD_IGNORE_RETURN;
766 exec_result = execute_until_command (command->value.While);
771 command->value.If->flags |= CMD_IGNORE_RETURN;
772 exec_result = execute_if_command (command->value.If);
777 /* This code can be executed from either of two paths: an explicit
778 '{}' command, or via a function call. If we are executed via a
779 function call, we have already taken care of the function being
780 executed in the background (down there in execute_simple_command ()),
781 and this command should *not* be marked as asynchronous. If we
782 are executing a regular '{}' group command, and asynchronous == 1,
783 we must want to execute the whole command in the background, so we
784 need a subshell, and we want the stuff executed in that subshell
785 (this group command) to be executed in the foreground of that
786 subshell (i.e. there will not be *another* subshell forked).
788 What we do is to force a subshell if asynchronous, and then call
789 execute_command_internal again with asynchronous still set to 1,
790 but with the original group command, so the printed command will
793 The code above that handles forking off subshells will note that
794 both subshell and async are on, and turn off async in the child
795 after forking the subshell (but leave async set in the parent, so
796 the normal call to describe_pid is made). This turning off
797 async is *crucial*; if it is not done, this will fall into an
798 infinite loop of executions through this spot in subshell after
799 subshell until the process limit is exhausted. */
803 command->flags |= CMD_FORCE_SUBSHELL;
805 execute_command_internal (command, 1, pipe_in, pipe_out,
810 if (ignore_return && command->value.Group->command)
811 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
813 execute_command_internal (command->value.Group->command,
814 asynchronous, pipe_in, pipe_out,
820 exec_result = execute_connection (command, asynchronous,
821 pipe_in, pipe_out, fds_to_close);
824 #if defined (DPAREN_ARITHMETIC)
827 command->value.Arith->flags |= CMD_IGNORE_RETURN;
828 exec_result = execute_arith_command (command->value.Arith);
832 #if defined (COND_COMMAND)
835 command->value.Cond->flags |= CMD_IGNORE_RETURN;
836 save_line_number = line_number;
837 exec_result = execute_cond_command (command->value.Cond);
838 line_number = save_line_number;
842 case cm_function_def:
843 exec_result = execute_intern_function (command->value.Function_def->name,
844 command->value.Function_def->command);
848 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
853 do_redirections (my_undo_list, RX_ACTIVE);
854 dispose_redirects (my_undo_list);
858 dispose_redirects (exec_undo_list);
860 if (my_undo_list || exec_undo_list)
861 discard_unwind_frame ("loop_redirections");
863 /* Invert the return value if we have to */
865 exec_result = (exec_result == EXECUTION_SUCCESS)
869 last_command_exit_value = exec_result;
870 run_pending_traps ();
872 if (running_trap == 0)
874 currently_executing_command = (COMMAND *)NULL;
875 return (last_command_exit_value);
878 #if defined (COMMAND_TIMING)
880 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
881 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
882 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
883 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
886 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
887 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
889 static int precs[] = { 0, 100, 10, 1 };
891 /* Expand one `%'-prefixed escape sequence from a time format string. */
893 mkfmt (buf, prec, lng, sec, sec_fraction)
900 char abuf[INT_STRLEN_BOUND(time_t) + 1];
904 abuf[sizeof(abuf) - 1] = '\0';
906 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
911 aind = sizeof(abuf) - 2;
913 abuf[aind--] = (min % 10) + '0';
917 buf[ind++] = abuf[aind++];
921 /* Now add the seconds. */
922 aind = sizeof (abuf) - 2;
924 abuf[aind--] = (sec % 10) + '0';
928 buf[ind++] = abuf[aind++];
930 /* We want to add a decimal point and PREC places after it if PREC is
931 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
936 for (aind = 1; aind <= prec; aind++)
938 buf[ind++] = (sec_fraction / precs[aind]) + '0';
939 sec_fraction %= precs[aind];
950 /* Interpret the format string FORMAT, interpolating the following escape
954 where the optional `prec' is a precision, meaning the number of
955 characters after the decimal point, the optional `l' means to format
956 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
957 and the last character is one of
959 R number of seconds of `real' time
960 U number of seconds of `user' time
961 S number of seconds of `system' time
963 An occurrence of `%%' in the format string is translated to a `%'. The
964 result is printed to FP, a pointer to a FILE. The other variables are
965 the seconds and thousandths of a second of real, user, and system time,
968 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
979 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
984 len = strlen (format);
985 ssize = (len + 64) - (len % 64);
986 str = (char *)xmalloc (ssize);
989 for (s = format; *s; s++)
991 if (*s != '%' || s[1] == '\0')
993 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
996 else if (s[1] == '%')
999 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1002 else if (s[1] == 'P')
1008 sum_frac = (cpu % 100) * 10;
1009 len = mkfmt (ts, 2, 0, sum, sum_frac);
1010 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1011 strcpy (str + sindex, ts);
1016 prec = 3; /* default is three places past the decimal point. */
1017 lng = 0; /* default is to not use minutes or append `s' */
1019 if (DIGIT (*s)) /* `precision' */
1022 if (prec > 3) prec = 3;
1024 if (*s == 'l') /* `length extender' */
1029 if (*s == 'R' || *s == 'E')
1030 len = mkfmt (ts, prec, lng, rs, rsf);
1032 len = mkfmt (ts, prec, lng, us, usf);
1034 len = mkfmt (ts, prec, lng, ss, ssf);
1037 internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1041 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1042 strcpy (str + sindex, ts);
1048 fprintf (fp, "%s\n", str);
1055 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1057 int asynchronous, pipe_in, pipe_out;
1058 struct fd_bitmap *fds_to_close;
1060 int rv, posix_time, old_flags;
1066 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1067 struct timeval real, user, sys;
1068 struct timeval before, after;
1069 # if defined (HAVE_STRUCT_TIMEZONE)
1070 struct timezone dtz; /* posix doesn't define this */
1072 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1074 # if defined (HAVE_TIMES)
1075 clock_t tbefore, tafter, real, user, sys;
1076 struct tms before, after;
1080 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1081 # if defined (HAVE_STRUCT_TIMEZONE)
1082 gettimeofday (&before, &dtz);
1084 gettimeofday (&before, (void *)NULL);
1085 # endif /* !HAVE_STRUCT_TIMEZONE */
1086 getrusage (RUSAGE_SELF, &selfb);
1087 getrusage (RUSAGE_CHILDREN, &kidsb);
1089 # if defined (HAVE_TIMES)
1090 tbefore = times (&before);
1094 posix_time = (command->flags & CMD_TIME_POSIX);
1096 old_flags = command->flags;
1097 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1098 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1099 command->flags = old_flags;
1102 rsf = usf = ssf = cpu = 0;
1104 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1105 # if defined (HAVE_STRUCT_TIMEZONE)
1106 gettimeofday (&after, &dtz);
1108 gettimeofday (&after, (void *)NULL);
1109 # endif /* !HAVE_STRUCT_TIMEZONE */
1110 getrusage (RUSAGE_SELF, &selfa);
1111 getrusage (RUSAGE_CHILDREN, &kidsa);
1113 difftimeval (&real, &before, &after);
1114 timeval_to_secs (&real, &rs, &rsf);
1116 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1117 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1118 timeval_to_secs (&user, &us, &usf);
1120 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1121 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1122 timeval_to_secs (&sys, &ss, &ssf);
1124 cpu = timeval_to_cpu (&real, &user, &sys);
1126 # if defined (HAVE_TIMES)
1127 tafter = times (&after);
1129 real = tafter - tbefore;
1130 clock_t_to_secs (real, &rs, &rsf);
1132 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1133 clock_t_to_secs (user, &us, &usf);
1135 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1136 clock_t_to_secs (sys, &ss, &ssf);
1138 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1142 rsf = usf = ssf = cpu = 0;
1147 time_format = POSIX_TIMEFORMAT;
1148 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1149 time_format = BASH_TIMEFORMAT;
1151 if (time_format && *time_format)
1152 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1156 #endif /* COMMAND_TIMING */
1158 /* Execute a command that's supposed to be in a subshell. This must be
1159 called after make_child and we must be running in the child process.
1160 The caller will return or exit() immediately with the value this returns. */
1162 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1165 int pipe_in, pipe_out;
1166 struct fd_bitmap *fds_to_close;
1168 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1172 USE_VAR(user_subshell);
1175 USE_VAR(asynchronous);
1178 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1179 pipe_in == NO_PIPE &&
1180 stdin_redirects (command->redirects) == 0);
1182 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1183 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1185 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1187 /* If a command is asynchronous in a subshell (like ( foo ) & or
1188 the special case of an asynchronous GROUP command where the
1189 the subshell bit is turned on down in case cm_group: below),
1190 turn off `asynchronous', so that two subshells aren't spawned.
1192 This seems semantically correct to me. For example,
1193 ( foo ) & seems to say ``do the command `foo' in a subshell
1194 environment, but don't wait for that subshell to finish'',
1195 and "{ foo ; bar ; } &" seems to me to be like functions or
1196 builtins in the background, which executed in a subshell
1197 environment. I just don't see the need to fork two subshells. */
1199 /* Don't fork again, we are already in a subshell. A `doubly
1200 async' shell is not interactive, however. */
1203 #if defined (JOB_CONTROL)
1204 /* If a construct like ( exec xxx yyy ) & is given while job
1205 control is active, we want to prevent exec from putting the
1206 subshell back into the original process group, carefully
1207 undoing all the work we just did in make_child. */
1209 #endif /* JOB_CONTROL */
1210 ois = interactive_shell;
1211 interactive_shell = 0;
1212 /* This test is to prevent alias expansion by interactive shells that
1213 run `(command) &' but to allow scripts that have enabled alias
1214 expansion with `shopt -s expand_alias' to continue to expand
1216 if (ois != interactive_shell)
1221 /* Subshells are neither login nor interactive. */
1222 login_shell = interactive = 0;
1224 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
1226 reset_terminating_signals (); /* in sig.c */
1227 /* Cancel traps, in trap.c. */
1228 restore_original_signals ();
1230 setup_async_signals ();
1232 #if defined (JOB_CONTROL)
1233 set_sigchld_handler ();
1234 #endif /* JOB_CONTROL */
1236 set_sigint_handler ();
1238 #if defined (JOB_CONTROL)
1239 /* Delete all traces that there were any jobs running. This is
1240 only for subshells. */
1241 without_job_control ();
1242 #endif /* JOB_CONTROL */
1245 close_fd_bitmap (fds_to_close);
1247 do_piping (pipe_in, pipe_out);
1249 /* If this is a user subshell, set a flag if stdin was redirected.
1250 This is used later to decide whether to redirect fd 0 to
1251 /dev/null for async commands in the subshell. This adds more
1252 sh compatibility, but I'm not sure it's the right thing to do. */
1255 stdin_redir = stdin_redirects (command->redirects);
1256 restore_default_signal (0);
1259 /* If this is an asynchronous command (command &), we want to
1260 redirect the standard input from /dev/null in the absence of
1261 any specific redirection involving stdin. */
1262 if (should_redir_stdin && stdin_redir == 0)
1263 async_redirect_stdin ();
1265 /* Do redirections, then dispose of them before recursive call. */
1266 if (command->redirects)
1268 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1269 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1271 dispose_redirects (command->redirects);
1272 command->redirects = (REDIRECT *)NULL;
1275 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1277 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1278 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1279 tcom->flags |= CMD_IGNORE_RETURN;
1281 /* If this is a simple command, tell execute_disk_command that it
1282 might be able to get away without forking and simply exec.
1283 This means things like ( sleep 10 ) will only cause one fork.
1284 If we're timing the command or inverting its return value, however,
1285 we cannot do this optimization. */
1286 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1287 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1288 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1290 tcom->flags |= CMD_NO_FORK;
1291 if (tcom->type == cm_simple)
1292 tcom->value.Simple->flags |= CMD_NO_FORK;
1295 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1296 tcom->flags &= ~CMD_INVERT_RETURN;
1298 /* If we're inside a function while executing this subshell, we
1299 need to handle a possible `return'. */
1301 if (return_catch_flag)
1302 function_value = setjmp (return_catch);
1305 return_code = return_catch_value;
1307 return_code = execute_command_internal
1308 (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1310 /* If we are asked to, invert the return value. */
1312 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1313 : EXECUTION_SUCCESS;
1315 /* If we were explicitly placed in a subshell with (), we need
1316 to do the `shell cleanup' things, such as running traps[0]. */
1317 if (user_subshell && signal_is_trapped (0))
1319 last_command_exit_value = return_code;
1320 return_code = run_exit_trap ();
1324 return (return_code);
1329 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1331 int asynchronous, pipe_in, pipe_out;
1332 struct fd_bitmap *fds_to_close;
1334 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1336 struct fd_bitmap *fd_bitmap;
1338 #if defined (JOB_CONTROL)
1340 BLOCK_CHILD (set, oset);
1341 #endif /* JOB_CONTROL */
1343 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1348 while (cmd && cmd->type == cm_connection &&
1349 cmd->value.Connection && cmd->value.Connection->connector == '|')
1351 /* Make a pipeline between the two commands. */
1352 if (pipe (fildes) < 0)
1354 sys_error ("pipe error");
1355 #if defined (JOB_CONTROL)
1356 terminate_current_pipeline ();
1357 kill_current_pipeline ();
1358 #endif /* JOB_CONTROL */
1359 last_command_exit_value = EXECUTION_FAILURE;
1360 /* The unwind-protects installed below will take care
1361 of closing all of the open file descriptors. */
1362 throw_to_top_level ();
1363 return (EXECUTION_FAILURE); /* XXX */
1366 /* Here is a problem: with the new file close-on-exec
1367 code, the read end of the pipe (fildes[0]) stays open
1368 in the first process, so that process will never get a
1369 SIGPIPE. There is no way to signal the first process
1370 that it should close fildes[0] after forking, so it
1371 remains open. No SIGPIPE is ever sent because there
1372 is still a file descriptor open for reading connected
1373 to the pipe. We take care of that here. This passes
1374 around a bitmap of file descriptors that must be
1375 closed after making a child process in execute_simple_command. */
1377 /* We need fd_bitmap to be at least as big as fildes[0].
1378 If fildes[0] is less than fds_to_close->size, then
1379 use fds_to_close->size. */
1380 new_bitmap_size = (fildes[0] < fds_to_close->size)
1381 ? fds_to_close->size
1384 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1386 /* Now copy the old information into the new bitmap. */
1387 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1389 /* And mark the pipe file descriptors to be closed. */
1390 fd_bitmap->bitmap[fildes[0]] = 1;
1392 /* In case there are pipe or out-of-processes errors, we
1393 want all these file descriptors to be closed when
1394 unwind-protects are run, and the storage used for the
1395 bitmaps freed up. */
1396 begin_unwind_frame ("pipe-file-descriptors");
1397 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1398 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1400 add_unwind_protect (close, prev);
1401 dummyfd = fildes[1];
1402 add_unwind_protect (close, dummyfd);
1404 #if defined (JOB_CONTROL)
1405 add_unwind_protect (restore_signal_mask, &oset);
1406 #endif /* JOB_CONTROL */
1408 if (ignore_return && cmd->value.Connection->first)
1409 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1410 execute_command_internal (cmd->value.Connection->first, asynchronous,
1411 prev, fildes[1], fd_bitmap);
1419 dispose_fd_bitmap (fd_bitmap);
1420 discard_unwind_frame ("pipe-file-descriptors");
1422 cmd = cmd->value.Connection->second;
1425 /* Now execute the rightmost command in the pipeline. */
1426 if (ignore_return && cmd)
1427 cmd->flags |= CMD_IGNORE_RETURN;
1428 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1433 #if defined (JOB_CONTROL)
1434 UNBLOCK_CHILD (oset);
1437 return (exec_result);
1441 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1443 int asynchronous, pipe_in, pipe_out;
1444 struct fd_bitmap *fds_to_close;
1447 COMMAND *tc, *second;
1448 int ignore_return, exec_result;
1450 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1452 switch (command->value.Connection->connector)
1454 /* Do the first command asynchronously. */
1456 tc = command->value.Connection->first;
1458 return (EXECUTION_SUCCESS);
1463 tc->flags |= CMD_IGNORE_RETURN;
1464 tc->flags |= CMD_AMPERSAND;
1466 /* If this shell was compiled without job control support,
1467 if we are currently in a subshell via `( xxx )', or if job
1468 control is not active then the standard input for an
1469 asynchronous command is forced to /dev/null. */
1470 #if defined (JOB_CONTROL)
1471 if ((subshell_environment || !job_control) && !stdin_redir)
1474 #endif /* JOB_CONTROL */
1475 tc->flags |= CMD_STDIN_REDIR;
1477 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1479 if (tc->flags & CMD_STDIN_REDIR)
1480 tc->flags &= ~CMD_STDIN_REDIR;
1482 second = command->value.Connection->second;
1486 second->flags |= CMD_IGNORE_RETURN;
1488 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1493 /* Just call execute command on both sides. */
1497 if (command->value.Connection->first)
1498 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1499 if (command->value.Connection->second)
1500 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1503 execute_command (command->value.Connection->first);
1505 exec_result = execute_command_internal (command->value.Connection->second,
1506 asynchronous, pipe_in, pipe_out,
1511 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1518 /* If we have something like `a && b &' or `a || b &', run the
1519 && or || stuff in a subshell. Force a subshell and just call
1520 execute_command_internal again. Leave asynchronous on
1521 so that we get a report from the parent shell about the
1523 command->flags |= CMD_FORCE_SUBSHELL;
1524 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1528 /* Execute the first command. If the result of that is successful
1529 and the connector is AND_AND, or the result is not successful
1530 and the connector is OR_OR, then execute the second command,
1531 otherwise return. */
1533 if (command->value.Connection->first)
1534 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1536 exec_result = execute_command (command->value.Connection->first);
1538 if (((command->value.Connection->connector == AND_AND) &&
1539 (exec_result == EXECUTION_SUCCESS)) ||
1540 ((command->value.Connection->connector == OR_OR) &&
1541 (exec_result != EXECUTION_SUCCESS)))
1543 if (ignore_return && command->value.Connection->second)
1544 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1546 exec_result = execute_command (command->value.Connection->second);
1551 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
1552 jump_to_top_level (DISCARD);
1553 exec_result = EXECUTION_FAILURE;
1562 if (!interactive_shell) \
1563 reap_dead_jobs (); \
1567 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1570 execute_for_command (for_command)
1571 FOR_COM *for_command;
1573 register WORD_LIST *releaser, *list;
1576 int retval, save_line_number;
1578 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1581 save_line_number = line_number;
1582 if (check_identifier (for_command->name, 1) == 0)
1584 if (posixly_correct && interactive_shell == 0)
1586 last_command_exit_value = EX_USAGE;
1587 jump_to_top_level (ERREXIT);
1589 return (EXECUTION_FAILURE);
1593 identifier = for_command->name->word;
1595 list = releaser = expand_words_no_vars (for_command->map_list);
1597 begin_unwind_frame ("for");
1598 add_unwind_protect (dispose_words, releaser);
1601 if (lexical_scoping)
1603 old_value = copy_variable (find_variable (identifier));
1605 add_unwind_protect (dispose_variable, old_value);
1609 if (for_command->flags & CMD_IGNORE_RETURN)
1610 for_command->action->flags |= CMD_IGNORE_RETURN;
1612 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1616 line_number = for_command->line;
1618 /* Remember what this command looks like, for debugger. */
1619 command_string_index = 0;
1620 print_for_command_head (for_command);
1622 if (echo_command_at_execute)
1623 xtrace_print_for_command_head (for_command);
1625 /* Save this command unless it's a trap command. */
1626 if (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0))
1628 FREE (the_printed_command_except_trap);
1629 the_printed_command_except_trap = savestring (the_printed_command);
1632 retval = run_debug_trap ();
1633 #if defined (DEBUGGER)
1634 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1635 skip the command. */
1636 if (debugging_mode && retval != EXECUTION_SUCCESS)
1640 this_command_name = (char *)NULL;
1641 v = bind_variable (identifier, list->word->word);
1642 if (readonly_p (v) || noassign_p (v))
1644 line_number = save_line_number;
1645 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1647 last_command_exit_value = EXECUTION_FAILURE;
1648 jump_to_top_level (FORCE_EOF);
1652 dispose_words (releaser);
1653 discard_unwind_frame ("for");
1655 return (EXECUTION_FAILURE);
1658 retval = execute_command (for_command->action);
1677 line_number = save_line_number;
1680 if (lexical_scoping)
1683 unbind_variable (identifier);
1686 SHELL_VAR *new_value;
1688 new_value = bind_variable (identifier, value_cell(old_value));
1689 new_value->attributes = old_value->attributes;
1690 dispose_variable (old_value);
1695 dispose_words (releaser);
1696 discard_unwind_frame ("for");
1700 #if defined (ARITH_FOR_COMMAND)
1701 /* Execute an arithmetic for command. The syntax is
1703 for (( init ; step ; test ))
1708 The execution should be exactly equivalent to
1711 while eval \(\( test \)\) ; do
1717 eval_arith_for_expr (l, okp)
1725 new = expand_words_no_vars (l);
1728 if (echo_command_at_execute)
1729 xtrace_print_arith_cmd (new);
1730 this_command_name = "(("; /* )) for expression error messages */
1732 command_string_index = 0;
1733 print_arith_command (new);
1734 FREE (the_printed_command_except_trap);
1735 the_printed_command_except_trap = savestring (the_printed_command);
1737 r = run_debug_trap ();
1738 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
1739 skip the command. */
1740 #if defined (DEBUGGER)
1741 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
1742 expresult = evalexp (new->word->word, okp);
1750 expresult = evalexp (new->word->word, okp);
1752 dispose_words (new);
1764 execute_arith_for_command (arith_for_command)
1765 ARITH_FOR_COM *arith_for_command;
1768 int expok, body_status, arith_lineno, save_lineno;
1770 body_status = EXECUTION_SUCCESS;
1772 save_lineno = line_number;
1774 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1775 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1777 this_command_name = "(("; /* )) for expression error messages */
1779 /* save the starting line number of the command so we can reset
1780 line_number before executing each expression -- for $LINENO
1781 and the DEBUG trap. */
1782 line_number = arith_lineno = arith_for_command->line;
1783 if (variable_context && interactive_shell)
1784 line_number -= function_line_number;
1786 /* Evaluate the initialization expression. */
1787 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1790 line_number = save_lineno;
1791 return (EXECUTION_FAILURE);
1796 /* Evaluate the test expression. */
1797 line_number = arith_lineno;
1798 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
1799 line_number = save_lineno;
1803 body_status = EXECUTION_FAILURE;
1810 /* Execute the body of the arithmetic for command. */
1812 body_status = execute_command (arith_for_command->action);
1815 /* Handle any `break' or `continue' commands executed by the body. */
1829 /* Evaluate the step expression. */
1830 line_number = arith_lineno;
1831 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
1832 line_number = save_lineno;
1836 body_status = EXECUTION_FAILURE;
1842 line_number = save_lineno;
1844 return (body_status);
1848 #if defined (SELECT_COMMAND)
1849 static int LINES, COLS, tabsize;
1851 #define RP_SPACE ") "
1852 #define RP_SPACE_LEN 2
1854 /* XXX - does not handle numbers > 1000000 at all. */
1855 #define NUMBER_LEN(s) \
1859 : ((s < 10000) ? 4 \
1860 : ((s < 100000) ? 5 \
1864 print_index_and_element (len, ind, list)
1868 register WORD_LIST *l;
1873 for (i = ind, l = list; l && --i; l = l->next)
1875 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1876 return (STRLEN (l->word->word));
1885 if ((to / tabsize) > (from / tabsize))
1887 putc ('\t', stderr);
1888 from += tabsize - from % tabsize;
1899 print_select_list (list, list_len, max_elem_len, indices_len)
1901 int list_len, max_elem_len, indices_len;
1903 int ind, row, elem_len, pos, cols, rows;
1904 int first_column_indices_len, other_indices_len;
1908 putc ('\n', stderr);
1912 cols = max_elem_len ? COLS / max_elem_len : 1;
1915 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1916 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1924 first_column_indices_len = NUMBER_LEN (rows);
1925 other_indices_len = indices_len;
1927 for (row = 0; row < rows; row++)
1933 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1934 elem_len = print_index_and_element (indices_len, ind + 1, list);
1935 elem_len += indices_len + RP_SPACE_LEN;
1937 if (ind >= list_len)
1939 indent (pos + elem_len, pos + max_elem_len);
1940 pos += max_elem_len;
1942 putc ('\n', stderr);
1946 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1947 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1948 If the number is between 1 and LIST_LEN, return that selection. If EOF
1949 is read, return a null string. If a blank line is entered, or an invalid
1950 number is entered, the loop is executed again. */
1952 select_query (list, list_len, prompt, print_menu)
1958 int max_elem_len, indices_len, len;
1961 char *repl_string, *t;
1963 t = get_string_value ("LINES");
1964 LINES = (t && *t) ? atoi (t) : 24;
1965 t = get_string_value ("COLUMNS");
1966 COLS = (t && *t) ? atoi (t) : 80;
1969 t = get_string_value ("TABSIZE");
1970 tabsize = (t && *t) ? atoi (t) : 8;
1978 for (l = list; l; l = l->next)
1980 len = STRLEN (l->word->word);
1981 if (len > max_elem_len)
1984 indices_len = NUMBER_LEN (list_len);
1985 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1990 print_select_list (list, list_len, max_elem_len, indices_len);
1991 fprintf (stderr, "%s", prompt);
1995 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1998 return ((char *)NULL);
2000 repl_string = get_string_value ("REPLY");
2001 if (*repl_string == 0)
2006 if (legal_number (repl_string, &reply) == 0)
2008 if (reply < 1 || reply > list_len)
2011 for (l = list; l && --reply; l = l->next)
2013 return (l->word->word);
2017 /* Execute a SELECT command. The syntax is:
2018 SELECT word IN list DO command_list DONE
2019 Only `break' or `return' in command_list will terminate
2022 execute_select_command (select_command)
2023 SELECT_COM *select_command;
2025 WORD_LIST *releaser, *list;
2027 char *identifier, *ps3_prompt, *selection;
2028 int retval, list_len, show_menu, save_line_number;
2030 if (check_identifier (select_command->name, 1) == 0)
2031 return (EXECUTION_FAILURE);
2033 save_line_number = line_number;
2034 line_number = select_command->line;
2036 command_string_index = 0;
2037 print_select_command_head (select_command);
2039 if (echo_command_at_execute)
2040 xtrace_print_select_command_head (select_command);
2042 FREE (the_printed_command_except_trap);
2043 the_printed_command_except_trap = savestring (the_printed_command);
2045 retval = run_debug_trap ();
2046 #if defined (DEBUGGER)
2047 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2048 skip the command. */
2049 if (debugging_mode && retval != EXECUTION_SUCCESS)
2050 return (EXECUTION_SUCCESS);
2054 identifier = select_command->name->word;
2056 /* command and arithmetic substitution, parameter and variable expansion,
2057 word splitting, pathname expansion, and quote removal. */
2058 list = releaser = expand_words_no_vars (select_command->map_list);
2059 list_len = list_length (list);
2060 if (list == 0 || list_len == 0)
2063 dispose_words (list);
2064 line_number = save_line_number;
2065 return (EXECUTION_SUCCESS);
2068 begin_unwind_frame ("select");
2069 add_unwind_protect (dispose_words, releaser);
2071 if (select_command->flags & CMD_IGNORE_RETURN)
2072 select_command->action->flags |= CMD_IGNORE_RETURN;
2074 retval = EXECUTION_SUCCESS;
2079 line_number = select_command->line;
2080 ps3_prompt = get_string_value ("PS3");
2081 if (ps3_prompt == 0)
2085 selection = select_query (list, list_len, ps3_prompt, show_menu);
2089 /* select_query returns EXECUTION_FAILURE if the read builtin
2090 fails, so we want to return failure in this case. */
2091 retval = EXECUTION_FAILURE;
2095 v = bind_variable (identifier, selection);
2096 if (readonly_p (v) || noassign_p (v))
2098 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
2100 last_command_exit_value = EXECUTION_FAILURE;
2101 jump_to_top_level (FORCE_EOF);
2105 dispose_words (releaser);
2106 discard_unwind_frame ("select");
2108 line_number = save_line_number;
2109 return (EXECUTION_FAILURE);
2113 retval = execute_command (select_command->action);
2131 #if defined (KSH_COMPATIBLE_SELECT)
2133 selection = get_string_value ("REPLY");
2134 if (selection && *selection == '\0')
2140 line_number = save_line_number;
2142 dispose_words (releaser);
2143 discard_unwind_frame ("select");
2146 #endif /* SELECT_COMMAND */
2148 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2149 The pattern_list is a linked list of pattern clauses; each clause contains
2150 some patterns to compare word_desc against, and an associated command to
2153 execute_case_command (case_command)
2154 CASE_COM *case_command;
2156 register WORD_LIST *list;
2157 WORD_LIST *wlist, *es;
2158 PATTERN_LIST *clauses;
2159 char *word, *pattern;
2160 int retval, match, ignore_return, save_line_number;
2162 save_line_number = line_number;
2163 line_number = case_command->line;
2165 command_string_index = 0;
2166 print_case_command_head (case_command);
2168 if (echo_command_at_execute)
2169 xtrace_print_case_command_head (case_command);
2171 if (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0))
2173 FREE (the_printed_command_except_trap);
2174 the_printed_command_except_trap = savestring (the_printed_command);
2177 retval = run_debug_trap();
2178 #if defined (DEBUGGER)
2179 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2180 skip the command. */
2181 if (debugging_mode && retval != EXECUTION_SUCCESS)
2183 line_number = save_line_number;
2184 return (EXECUTION_SUCCESS);
2188 /* Posix.2 specifies that the WORD is tilde expanded. */
2189 if (member ('~', case_command->word->word))
2191 word = bash_tilde_expand (case_command->word->word, 0);
2192 free (case_command->word->word);
2193 case_command->word->word = word;
2196 wlist = expand_word_unsplit (case_command->word, 0);
2197 word = wlist ? string_list (wlist) : savestring ("");
2198 dispose_words (wlist);
2200 retval = EXECUTION_SUCCESS;
2201 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2203 begin_unwind_frame ("case");
2204 add_unwind_protect ((Function *)xfree, word);
2206 #define EXIT_CASE() goto exit_case_command
2208 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2211 for (list = clauses->patterns; list; list = list->next)
2213 /* Posix.2 specifies to tilde expand each member of the pattern
2215 if (member ('~', list->word->word))
2217 pattern = bash_tilde_expand (list->word->word, 0);
2218 free (list->word->word);
2219 list->word->word = pattern;
2222 es = expand_word_leave_quoted (list->word, 0);
2224 if (es && es->word && es->word->word && *(es->word->word))
2225 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2228 pattern = (char *)xmalloc (1);
2232 /* Since the pattern does not undergo quote removal (as per
2233 Posix.2, section 3.9.4.3), the strmatch () call must be able
2234 to recognize backslashes as escape characters. */
2235 match = strmatch (pattern, word, FNMATCH_EXTFLAG) != FNM_NOMATCH;
2242 if (clauses->action && ignore_return)
2243 clauses->action->flags |= CMD_IGNORE_RETURN;
2244 retval = execute_command (clauses->action);
2254 discard_unwind_frame ("case");
2255 line_number = save_line_number;
2262 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2263 Repeatedly execute action while executing test produces
2264 EXECUTION_SUCCESS. */
2266 execute_while_command (while_command)
2267 WHILE_COM *while_command;
2269 return (execute_while_or_until (while_command, CMD_WHILE));
2272 /* UNTIL is just like WHILE except that the test result is negated. */
2274 execute_until_command (while_command)
2275 WHILE_COM *while_command;
2277 return (execute_while_or_until (while_command, CMD_UNTIL));
2280 /* The body for both while and until. The only difference between the
2281 two is that the test value is treated differently. TYPE is
2282 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2283 be EXECUTION_SUCCESS if no commands in the body are executed, and
2284 the status of the last command executed in the body otherwise. */
2286 execute_while_or_until (while_command, type)
2287 WHILE_COM *while_command;
2290 int return_value, body_status;
2292 body_status = EXECUTION_SUCCESS;
2295 while_command->test->flags |= CMD_IGNORE_RETURN;
2296 if (while_command->flags & CMD_IGNORE_RETURN)
2297 while_command->action->flags |= CMD_IGNORE_RETURN;
2301 return_value = execute_command (while_command->test);
2304 /* Need to handle `break' in the test when we would break out of the
2305 loop. The job control code will set `breaking' to loop_level
2306 when a job in a loop is stopped with SIGTSTP. If the stopped job
2307 is in the loop test, `breaking' will not be reset unless we do
2308 this, and the shell will cease to execute commands. */
2309 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2315 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2323 body_status = execute_command (while_command->action);
2341 return (body_status);
2344 /* IF test THEN command [ELSE command].
2345 IF also allows ELIF in the place of ELSE IF, but
2346 the parser makes *that* stupidity transparent. */
2348 execute_if_command (if_command)
2351 int return_value, save_line_number;
2353 save_line_number = line_number;
2354 if_command->test->flags |= CMD_IGNORE_RETURN;
2355 return_value = execute_command (if_command->test);
2356 line_number = save_line_number;
2358 if (return_value == EXECUTION_SUCCESS)
2362 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2363 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2365 return (execute_command (if_command->true_case));
2371 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2372 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2374 return (execute_command (if_command->false_case));
2378 #if defined (DPAREN_ARITHMETIC)
2380 execute_arith_command (arith_command)
2381 ARITH_COM *arith_command;
2383 int expok, save_line_number, retval;
2389 save_line_number = line_number;
2390 this_command_name = "(("; /* )) */
2391 line_number = arith_command->line;
2392 /* If we're in a function, update the line number information. */
2393 if (variable_context && interactive_shell)
2394 line_number -= function_line_number;
2396 command_string_index = 0;
2397 print_arith_command (arith_command->exp);
2398 FREE (the_printed_command_except_trap);
2399 the_printed_command_except_trap = savestring (the_printed_command);
2401 /* Run the debug trap before each arithmetic command, but do it after we
2402 update the line number information and before we expand the various
2403 words in the expression. */
2404 retval = run_debug_trap ();
2405 #if defined (DEBUGGER)
2406 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2407 skip the command. */
2408 if (debugging_mode && retval != EXECUTION_SUCCESS)
2410 line_number = save_line_number;
2411 return (EXECUTION_SUCCESS);
2415 new = expand_words_no_vars (arith_command->exp);
2417 /* If we're tracing, make a new word list with `((' at the front and `))'
2418 at the back and print it. */
2419 if (echo_command_at_execute)
2420 xtrace_print_arith_cmd (new);
2424 expresult = evalexp (new->word->word, &expok);
2425 line_number = save_line_number;
2426 dispose_words (new);
2435 return (EXECUTION_FAILURE);
2437 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2439 #endif /* DPAREN_ARITHMETIC */
2441 #if defined (COND_COMMAND)
2443 static char *nullstr = "";
2446 execute_cond_node (cond)
2449 int result, invert, patmatch, rmatch, mflags;
2452 invert = (cond->flags & CMD_INVERT_RETURN);
2454 if (cond->type == COND_EXPR)
2455 result = execute_cond_node (cond->left);
2456 else if (cond->type == COND_OR)
2458 result = execute_cond_node (cond->left);
2459 if (result != EXECUTION_SUCCESS)
2460 result = execute_cond_node (cond->right);
2462 else if (cond->type == COND_AND)
2464 result = execute_cond_node (cond->left);
2465 if (result == EXECUTION_SUCCESS)
2466 result = execute_cond_node (cond->right);
2468 else if (cond->type == COND_UNARY)
2470 arg1 = cond_expand_word (cond->left->op, 0);
2473 if (echo_command_at_execute)
2474 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2475 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2476 if (arg1 != nullstr)
2479 else if (cond->type == COND_BINARY)
2481 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2482 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2483 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
2484 #if defined (COND_REGEXP)
2485 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
2486 cond->op->word[2] == '\0');
2489 arg1 = cond_expand_word (cond->left->op, 0);
2492 arg2 = cond_expand_word (cond->right->op, patmatch);
2496 if (echo_command_at_execute)
2497 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2499 #if defined (COND_REGEXP)
2502 mflags = SHMAT_PWARN;
2503 #if defined (ARRAY_VARS)
2504 mflags |= SHMAT_SUBEXP;
2507 result = sh_regmatch (arg1, arg2, mflags);
2510 #endif /* COND_REGEXP */
2511 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2513 : EXECUTION_FAILURE;
2514 if (arg1 != nullstr)
2516 if (arg2 != nullstr)
2521 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
2522 jump_to_top_level (DISCARD);
2523 result = EXECUTION_FAILURE;
2527 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2533 execute_cond_command (cond_command)
2534 COND_COM *cond_command;
2536 int retval, save_line_number;
2538 retval = EXECUTION_SUCCESS;
2539 save_line_number = line_number;
2541 this_command_name = "[[";
2542 line_number = cond_command->line;
2543 /* If we're in a function, update the line number information. */
2544 if (variable_context && interactive_shell)
2545 line_number -= function_line_number;
2547 command_string_index = 0;
2548 print_cond_command (cond_command);
2549 FREE (the_printed_command_except_trap);
2550 the_printed_command_except_trap = savestring (the_printed_command);
2552 /* Run the debug trap before each conditional command, but do it after we
2553 update the line number information. */
2554 retval = run_debug_trap ();
2555 #if defined (DEBUGGER)
2556 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2557 skip the command. */
2558 if (debugging_mode && retval != EXECUTION_SUCCESS)
2560 line_number = save_line_number;
2561 return (EXECUTION_SUCCESS);
2566 debug_print_cond_command (cond_command);
2569 last_command_exit_value = retval = execute_cond_node (cond_command);
2570 line_number = save_line_number;
2573 #endif /* COND_COMMAND */
2583 var = bind_variable ("_", arg);
2584 VUNSETATTR (var, att_exported);
2587 /* Execute a null command. Fork a subshell if the command uses pipes or is
2588 to be run asynchronously. This handles all the side effects that are
2589 supposed to take place. */
2591 execute_null_command (redirects, pipe_in, pipe_out, async, old_last_command_subst_pid)
2592 REDIRECT *redirects;
2593 int pipe_in, pipe_out, async;
2594 pid_t old_last_command_subst_pid;
2598 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2600 /* We have a null command, but we really want a subshell to take
2601 care of it. Just fork, do piping and redirections, and exit. */
2602 if (make_child ((char *)NULL, async) == 0)
2604 /* Cancel traps, in trap.c. */
2605 restore_original_signals (); /* XXX */
2607 do_piping (pipe_in, pipe_out);
2609 subshell_environment = SUBSHELL_ASYNC;
2611 if (do_redirections (redirects, RX_ACTIVE) == 0)
2612 exit (EXECUTION_SUCCESS);
2614 exit (EXECUTION_FAILURE);
2618 close_pipes (pipe_in, pipe_out);
2619 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2620 unlink_fifo_list ();
2622 return (EXECUTION_SUCCESS);
2627 /* Even if there aren't any command names, pretend to do the
2628 redirections that are specified. The user expects the side
2629 effects to take place. If the redirections fail, then return
2630 failure. Otherwise, if a command substitution took place while
2631 expanding the command or a redirection, return the value of that
2632 substitution. Otherwise, return EXECUTION_SUCCESS. */
2634 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
2635 cleanup_redirects (redirection_undo_list);
2636 redirection_undo_list = (REDIRECT *)NULL;
2639 return (EXECUTION_FAILURE);
2640 else if (old_last_command_subst_pid != last_command_subst_pid)
2641 return (last_command_exit_value);
2643 return (EXECUTION_SUCCESS);
2647 /* This is a hack to suppress word splitting for assignment statements
2648 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2650 fix_assignment_words (words)
2661 for (w = words; w; w = w->next)
2662 if (w->word->flags & W_ASSIGNMENT)
2666 b = builtin_address_internal (words->word->word, 0);
2667 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2670 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP);
2674 /* The meaty part of all the executions. We have to start hacking the
2675 real execution of commands here. Fork a process, set things up,
2676 execute the command. */
2678 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2679 SIMPLE_COM *simple_command;
2680 int pipe_in, pipe_out, async;
2681 struct fd_bitmap *fds_to_close;
2683 WORD_LIST *words, *lastword;
2684 char *command_line, *lastarg, *temp;
2685 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
2686 pid_t old_last_command_subst_pid, old_last_async_pid;
2687 sh_builtin_func_t *builtin;
2690 result = EXECUTION_SUCCESS;
2691 special_builtin_failed = builtin_is_special = 0;
2692 command_line = (char *)0;
2694 /* If we're in a function, update the line number information. */
2695 if (variable_context && interactive_shell)
2696 line_number -= function_line_number;
2698 /* Remember what this command line looks like at invocation. */
2699 command_string_index = 0;
2700 print_simple_command (simple_command);
2702 if (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0))
2704 FREE (the_printed_command_except_trap);
2705 the_printed_command_except_trap = savestring (the_printed_command);
2708 /* Run the debug trap before each simple command, but do it after we
2709 update the line number information. */
2710 result = run_debug_trap ();
2711 #if defined (DEBUGGER)
2712 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2713 skip the command. */
2714 if (debugging_mode && result != EXECUTION_SUCCESS)
2715 return (EXECUTION_SUCCESS);
2719 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2721 old_last_command_subst_pid = last_command_subst_pid;
2722 old_last_async_pid = last_asynchronous_pid;
2724 already_forked = dofork = 0;
2726 /* If we're in a pipeline or run in the background, set DOFORK so we
2727 make the child early, before word expansion. This keeps assignment
2728 statements from affecting the parent shell's environment when they
2730 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2732 /* Something like `%2 &' should restart job 2 in the background, not cause
2733 the shell to fork here. */
2734 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2735 simple_command->words && simple_command->words->word &&
2736 simple_command->words->word->word &&
2737 (simple_command->words->word->word[0] == '%'))
2743 /* XXX memory leak if expand_words() error causes a jump_to_top_level */
2744 command_line = savestring (the_printed_command);
2747 /* Do this now, because execute_disk_command will do it anyway in the
2748 vast majority of cases. */
2749 maybe_make_export_env ();
2752 if (make_child (command_line, async) == 0)
2754 if (make_child (savestring (the_printed_command), async) == 0)
2758 simple_command->flags |= CMD_NO_FORK;
2760 subshell_environment = (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2761 ? (SUBSHELL_PIPE|SUBSHELL_FORK)
2762 : (SUBSHELL_ASYNC|SUBSHELL_FORK);
2764 /* We need to do this before piping to handle some really
2765 pathological cases where one of the pipe file descriptors
2768 close_fd_bitmap (fds_to_close);
2770 do_piping (pipe_in, pipe_out);
2771 pipe_in = pipe_out = NO_PIPE;
2773 last_asynchronous_pid = old_last_async_pid;
2777 close_pipes (pipe_in, pipe_out);
2778 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2779 unlink_fifo_list ();
2781 command_line = (char *)NULL; /* don't free this. */
2782 bind_lastarg ((char *)NULL);
2787 /* If we are re-running this as the result of executing the `command'
2788 builtin, do not expand the command words a second time. */
2789 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2791 current_fds_to_close = fds_to_close;
2792 fix_assignment_words (simple_command->words);
2793 words = expand_words (simple_command->words);
2794 current_fds_to_close = (struct fd_bitmap *)NULL;
2797 words = copy_word_list (simple_command->words);
2799 /* It is possible for WORDS not to have anything left in it.
2800 Perhaps all the words consisted of `$foo', and there was
2801 no variable `$foo'. */
2804 this_command_name = 0;
2805 result = execute_null_command (simple_command->redirects,
2807 already_forked ? 0 : async,
2808 old_last_command_subst_pid);
2813 bind_lastarg ((char *)NULL);
2814 set_pipestatus_from_exit (result);
2819 lastarg = (char *)NULL;
2821 begin_unwind_frame ("simple-command");
2823 if (echo_command_at_execute)
2824 xtrace_print_word_list (words, 1);
2826 builtin = (sh_builtin_func_t *)NULL;
2827 func = (SHELL_VAR *)NULL;
2828 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2830 /* Posix.2 says special builtins are found before functions. We
2831 don't set builtin_is_special anywhere other than here, because
2832 this path is followed only when the `command' builtin is *not*
2833 being used, and we don't want to exit the shell if a special
2834 builtin executed with `command builtin' fails. `command' is not
2835 a special builtin. */
2836 if (posixly_correct)
2838 builtin = find_special_builtin (words->word->word);
2840 builtin_is_special = 1;
2843 func = find_function (words->word->word);
2846 /* In POSIX mode, assignment errors in the temporary environment cause a
2847 non-interactive shell to exit. */
2848 if (builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
2850 last_command_exit_value = EXECUTION_FAILURE;
2851 jump_to_top_level (ERREXIT);
2854 add_unwind_protect (dispose_words, words);
2857 /* Bind the last word in this command to "$_" after execution. */
2858 for (lastword = words; lastword->next; lastword = lastword->next)
2860 lastarg = lastword->word->word;
2862 #if defined (JOB_CONTROL)
2863 /* Is this command a job control related thing? */
2864 if (words->word->word[0] == '%' && already_forked == 0)
2866 this_command_name = async ? "bg" : "fg";
2867 last_shell_builtin = this_shell_builtin;
2868 this_shell_builtin = builtin_address (this_command_name);
2869 result = (*this_shell_builtin) (words);
2873 /* One other possiblilty. The user may want to resume an existing job.
2874 If they do, find out whether this word is a candidate for a running
2876 if (job_control && already_forked == 0 && async == 0 &&
2877 !first_word_quoted &&
2879 words->word->word[0] &&
2880 !simple_command->redirects &&
2881 pipe_in == NO_PIPE &&
2882 pipe_out == NO_PIPE &&
2883 (temp = get_string_value ("auto_resume")))
2885 int job, jflags, started_status;
2887 jflags = JM_STOPPED|JM_FIRSTMATCH;
2888 if (STREQ (temp, "exact"))
2890 else if (STREQ (temp, "substring"))
2891 jflags |= JM_SUBSTRING;
2893 jflags |= JM_PREFIX;
2894 job = get_job_by_name (words->word->word, jflags);
2897 run_unwind_frame ("simple-command");
2898 this_command_name = "fg";
2899 last_shell_builtin = this_shell_builtin;
2900 this_shell_builtin = builtin_address ("fg");
2902 started_status = start_job (job, 1);
2903 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2906 #endif /* JOB_CONTROL */
2908 /* Remember the name of this command globally. */
2909 this_command_name = words->word->word;
2913 /* This command could be a shell builtin or a user-defined function.
2914 We have already found special builtins by this time, so we do not
2915 set builtin_is_special. If this is a function or builtin, and we
2916 have pipes, then fork a subshell in here. Otherwise, just execute
2917 the command directly. */
2918 if (func == 0 && builtin == 0)
2919 builtin = find_shell_builtin (this_command_name);
2921 last_shell_builtin = this_shell_builtin;
2922 this_shell_builtin = builtin;
2924 if (builtin || func)
2928 /* reset_terminating_signals (); */ /* XXX */
2929 /* Cancel traps, in trap.c. */
2930 restore_original_signals ();
2934 if ((simple_command->flags & CMD_STDIN_REDIR) &&
2935 pipe_in == NO_PIPE &&
2936 (stdin_redirects (simple_command->redirects) == 0))
2937 async_redirect_stdin ();
2938 setup_async_signals ();
2942 execute_subshell_builtin_or_function
2943 (words, simple_command->redirects, builtin, func,
2944 pipe_in, pipe_out, async, fds_to_close,
2945 simple_command->flags);
2950 result = execute_builtin_or_function
2951 (words, builtin, func, simple_command->redirects, fds_to_close,
2952 simple_command->flags);
2955 if (result > EX_SHERRBASE)
2957 result = builtin_status (result);
2958 if (builtin_is_special)
2959 special_builtin_failed = 1;
2961 /* In POSIX mode, if there are assignment statements preceding
2962 a special builtin, they persist after the builtin
2964 if (posixly_correct && builtin_is_special && temporary_env)
2965 merge_temporary_env ();
2969 if (result == EX_USAGE)
2970 result = EX_BADUSAGE;
2971 else if (result > EX_SHERRBASE)
2972 result = EXECUTION_FAILURE;
2975 set_pipestatus_from_exit (result);
2981 if (command_line == 0)
2982 command_line = savestring (the_printed_command);
2984 execute_disk_command (words, simple_command->redirects, command_line,
2985 pipe_in, pipe_out, async, fds_to_close,
2986 simple_command->flags);
2989 bind_lastarg (lastarg);
2990 FREE (command_line);
2991 dispose_words (words);
2992 discard_unwind_frame ("simple-command");
2993 this_command_name = (char *)NULL; /* points to freed memory now */
2997 /* Translate the special builtin exit statuses. We don't really need a
2998 function for this; it's a placeholder for future work. */
3000 builtin_status (result)
3014 r = EXECUTION_FAILURE;
3017 r = EXECUTION_SUCCESS;
3024 execute_builtin (builtin, words, flags, subshell)
3025 sh_builtin_func_t *builtin;
3027 int flags, subshell;
3029 int old_e_flag, result, eval_unwind;
3032 old_e_flag = exit_immediately_on_error;
3033 /* The eval builtin calls parse_and_execute, which does not know about
3034 the setting of flags, and always calls the execution functions with
3035 flags that will exit the shell on an error if -e is set. If the
3036 eval builtin is being called, and we're supposed to ignore the exit
3037 value of the command, we turn the -e flag off ourselves, then
3038 restore it when the command completes. */
3039 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
3041 begin_unwind_frame ("eval_builtin");
3042 unwind_protect_int (exit_immediately_on_error);
3043 exit_immediately_on_error = 0;
3049 /* The temporary environment for a builtin is supposed to apply to
3050 all commands executed by that builtin. Currently, this is a
3051 problem only with the `source' and `eval' builtins. */
3052 isbltinenv = (builtin == source_builtin || builtin == eval_builtin);
3056 begin_unwind_frame ("builtin_env");
3060 push_scope (VC_BLTNENV, temporary_env);
3062 add_unwind_protect (pop_scope, "1");
3063 temporary_env = (HASH_TABLE *)NULL;
3067 /* `return' does a longjmp() back to a saved environment in execute_function.
3068 If a variable assignment list preceded the command, and the shell is
3069 running in POSIX mode, we need to merge that into the shell_variables
3070 table, since `return' is a POSIX special builtin. */
3071 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3073 begin_unwind_frame ("return_temp_env");
3074 add_unwind_protect (merge_temporary_env, (char *)NULL);
3077 result = ((*builtin) (words->next));
3079 /* This shouldn't happen, but in case `return' comes back instead of
3080 longjmp'ing, we need to unwind. */
3081 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
3082 discard_unwind_frame ("return_temp_env");
3084 if (subshell == 0 && isbltinenv)
3085 run_unwind_frame ("builtin_env");
3089 exit_immediately_on_error += old_e_flag;
3090 discard_unwind_frame ("eval_builtin");
3097 execute_function (var, words, flags, fds_to_close, async, subshell)
3101 struct fd_bitmap *fds_to_close;
3102 int async, subshell;
3104 int return_val, result;
3105 COMMAND *tc, *fc, *save_current;
3106 char *debug_trap, *error_trap, *return_trap;
3107 #if defined (ARRAY_VARS)
3108 SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
3109 ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
3111 FUNCTION_DEF *shell_fn;
3113 static int funcnest = 0;
3117 #if defined (ARRAY_VARS)
3118 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
3119 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
3120 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
3123 tc = (COMMAND *)copy_command (function_cell (var));
3124 if (tc && (flags & CMD_IGNORE_RETURN))
3125 tc->flags |= CMD_IGNORE_RETURN;
3129 begin_unwind_frame ("function_calling");
3130 push_context (var->name, subshell, temporary_env);
3131 add_unwind_protect (pop_context, (char *)NULL);
3132 unwind_protect_int (line_number);
3133 unwind_protect_int (return_catch_flag);
3134 unwind_protect_jmp_buf (return_catch);
3135 add_unwind_protect (dispose_command, (char *)tc);
3136 unwind_protect_pointer (this_shell_function);
3137 unwind_protect_int (loop_level);
3140 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
3142 temporary_env = (HASH_TABLE *)NULL;
3144 this_shell_function = var;
3145 make_funcname_visible (1);
3147 debug_trap = TRAP_STRING(DEBUG_TRAP);
3148 error_trap = TRAP_STRING(ERROR_TRAP);
3149 return_trap = TRAP_STRING(RETURN_TRAP);
3151 /* The order of the unwind protects for debug_trap, error_trap and
3152 return_trap is important here! unwind-protect commands are run
3153 in reverse order of registration. If this causes problems, take
3154 out the xfree unwind-protect calls and live with the small memory leak. */
3156 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
3157 if the function has the trace attribute set, it inherits the DEBUG trap */
3158 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
3162 debug_trap = savestring (debug_trap);
3163 add_unwind_protect (xfree, debug_trap);
3164 add_unwind_protect (set_debug_trap, debug_trap);
3166 restore_default_signal (DEBUG_TRAP);
3169 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
3170 if (error_trap && error_trace_mode == 0)
3174 error_trap = savestring (error_trap);
3175 add_unwind_protect (xfree, error_trap);
3176 add_unwind_protect (set_error_trap, error_trap);
3178 restore_default_signal (ERROR_TRAP);
3181 if (return_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
3185 return_trap = savestring (return_trap);
3186 add_unwind_protect (xfree, return_trap);
3187 add_unwind_protect (set_return_trap, return_trap);
3189 restore_default_signal (RETURN_TRAP);
3193 #if defined (ARRAY_VARS)
3194 /* This is quite similar to the code in shell.c and elsewhere. */
3195 shell_fn = find_function_def (this_shell_function->name);
3196 sfile = shell_fn ? shell_fn->source_file : "";
3197 array_push (funcname_a, this_shell_function->name);
3199 array_push (bash_source_a, sfile);
3200 t = itos (executing_line_number ());
3201 array_push (bash_lineno_a, t);
3205 /* The temporary environment for a function is supposed to apply to
3206 all commands executed within the function body. */
3208 remember_args (words->next, 1);
3210 /* Update BASH_ARGV and BASH_ARGC */
3212 push_args (words->next);
3214 /* Number of the line on which the function body starts. */
3215 line_number = function_line_number = tc->line;
3219 #if defined (JOB_CONTROL)
3220 stop_pipeline (async, (COMMAND *)NULL);
3222 fc = (tc->type == cm_group) ? tc->value.Group->command : tc;
3224 if (fc && (flags & CMD_IGNORE_RETURN))
3225 fc->flags |= CMD_IGNORE_RETURN;
3230 return_catch_flag++;
3231 return_val = setjmp (return_catch);
3234 result = return_catch_value;
3237 /* Run the debug trap here so we can trap at the start of a function's
3238 execution rather than the execution of the body's first command. */
3239 showing_function_line = 1;
3240 save_current = currently_executing_command;
3241 result = run_debug_trap ();
3242 #if defined (DEBUGGER)
3243 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3244 skip the command. */
3245 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
3247 showing_function_line = 0;
3248 currently_executing_command = save_current;
3249 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
3251 /* Run the RETURN trap in the function's context */
3252 save_current = currently_executing_command;
3254 currently_executing_command = save_current;
3257 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
3259 showing_function_line = 0;
3262 /* Restore BASH_ARGC and BASH_ARGV */
3267 run_unwind_frame ("function_calling");
3270 #if defined (ARRAY_VARS)
3271 array_pop (bash_source_a);
3272 array_pop (funcname_a);
3273 array_pop (bash_lineno_a);
3276 if (variable_context == 0 || this_shell_function == 0)
3277 make_funcname_visible (0);
3282 /* A convenience routine for use by other parts of the shell to execute
3283 a particular shell function. */
3285 execute_shell_function (var, words)
3290 struct fd_bitmap *bitmap;
3292 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
3293 begin_unwind_frame ("execute-shell-function");
3294 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
3296 ret = execute_function (var, words, 0, bitmap, 0, 0);
3298 dispose_fd_bitmap (bitmap);
3299 discard_unwind_frame ("execute-shell-function");
3304 /* Execute a shell builtin or function in a subshell environment. This
3305 routine does not return; it only calls exit(). If BUILTIN is non-null,
3306 it points to a function to call to execute a shell builtin; otherwise
3307 VAR points at the body of a function to execute. WORDS is the arguments
3308 to the command, REDIRECTS specifies redirections to perform before the
3309 command is executed. */
3311 execute_subshell_builtin_or_function (words, redirects, builtin, var,
3312 pipe_in, pipe_out, async, fds_to_close,
3315 REDIRECT *redirects;
3316 sh_builtin_func_t *builtin;
3318 int pipe_in, pipe_out, async;
3319 struct fd_bitmap *fds_to_close;
3323 #if defined (JOB_CONTROL)
3326 jobs_hack = (builtin == jobs_builtin) &&
3327 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
3330 /* A subshell is neither a login shell nor interactive. */
3331 login_shell = interactive = 0;
3333 subshell_environment = SUBSHELL_ASYNC;
3335 maybe_make_export_env (); /* XXX - is this needed? */
3337 #if defined (JOB_CONTROL)
3338 /* Eradicate all traces of job control after we fork the subshell, so
3339 all jobs begun by this subshell are in the same process group as
3340 the shell itself. */
3342 /* Allow the output of `jobs' to be piped. */
3344 kill_current_pipeline ();
3346 without_job_control ();
3348 set_sigchld_handler ();
3349 #endif /* JOB_CONTROL */
3351 set_sigint_handler ();
3354 close_fd_bitmap (fds_to_close);
3356 do_piping (pipe_in, pipe_out);
3358 if (do_redirections (redirects, RX_ACTIVE) != 0)
3359 exit (EXECUTION_FAILURE);
3363 /* Give builtins a place to jump back to on failure,
3364 so we don't go back up to main(). */
3365 result = setjmp (top_level);
3367 if (result == EXITPROG)
3368 exit (last_command_exit_value);
3370 exit (EXECUTION_FAILURE);
3373 r = execute_builtin (builtin, words, flags, 1);
3380 exit (execute_function (var, words, flags, fds_to_close, async, 1));
3383 /* Execute a builtin or function in the current shell context. If BUILTIN
3384 is non-null, it is the builtin command to execute, otherwise VAR points
3385 to the body of a function. WORDS are the command's arguments, REDIRECTS
3386 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
3387 file descriptors to close.
3389 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
3390 not undone before this function returns. */
3392 execute_builtin_or_function (words, builtin, var, redirects,
3393 fds_to_close, flags)
3395 sh_builtin_func_t *builtin;
3397 REDIRECT *redirects;
3398 struct fd_bitmap *fds_to_close;
3402 REDIRECT *saved_undo_list;
3403 sh_builtin_func_t *saved_this_shell_builtin;
3405 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
3407 cleanup_redirects (redirection_undo_list);
3408 redirection_undo_list = (REDIRECT *)NULL;
3409 dispose_exec_redirects ();
3410 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
3413 saved_this_shell_builtin = this_shell_builtin;
3414 saved_undo_list = redirection_undo_list;
3416 /* Calling the "exec" builtin changes redirections forever. */
3417 if (builtin == exec_builtin)
3419 dispose_redirects (saved_undo_list);
3420 saved_undo_list = exec_redirection_undo_list;
3421 exec_redirection_undo_list = (REDIRECT *)NULL;
3424 dispose_exec_redirects ();
3426 if (saved_undo_list)
3428 begin_unwind_frame ("saved redirects");
3429 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
3432 redirection_undo_list = (REDIRECT *)NULL;
3435 result = execute_builtin (builtin, words, flags, 0);
3437 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3439 /* We do this before undoing the effects of any redirections. */
3440 if (ferror (stdout))
3443 /* If we are executing the `command' builtin, but this_shell_builtin is
3444 set to `exec_builtin', we know that we have something like
3445 `command exec [redirection]', since otherwise `exec' would have
3446 overwritten the shell and we wouldn't get here. In this case, we
3447 want to behave as if the `command' builtin had not been specified
3448 and preserve the redirections. */
3449 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
3451 if (saved_undo_list)
3452 dispose_redirects (saved_undo_list);
3453 redirection_undo_list = exec_redirection_undo_list;
3454 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
3455 discard_unwind_frame ("saved_redirects");
3458 if (saved_undo_list)
3460 redirection_undo_list = saved_undo_list;
3461 discard_unwind_frame ("saved redirects");
3464 if (redirection_undo_list)
3466 cleanup_redirects (redirection_undo_list);
3467 redirection_undo_list = (REDIRECT *)NULL;
3474 setup_async_signals ()
3476 #if defined (__BEOS__)
3477 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3480 #if defined (JOB_CONTROL)
3481 if (job_control == 0)
3484 set_signal_handler (SIGINT, SIG_IGN);
3485 set_signal_ignored (SIGINT);
3486 set_signal_handler (SIGQUIT, SIG_IGN);
3487 set_signal_ignored (SIGQUIT);
3491 /* Execute a simple command that is hopefully defined in a disk file
3496 3) look up the command
3499 6) If the execve failed, see if the file has executable mode set.
3500 If so, and it isn't a directory, then execute its contents as
3503 Note that the filename hashing stuff has to take place up here,
3504 in the parent. This is probably why the Bourne style shells
3505 don't handle it, since that would require them to go through
3506 this gnarly hair, for no good reason.
3508 NOTE: callers expect this to fork or exit(). */
3510 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
3511 async, fds_to_close, cmdflags)
3513 REDIRECT *redirects;
3515 int pipe_in, pipe_out, async;
3516 struct fd_bitmap *fds_to_close;
3519 char *pathname, *command, **args;
3523 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
3524 pathname = words->word->word;
3526 #if defined (RESTRICTED_SHELL)
3527 command = (char *)NULL;
3528 if (restricted && xstrchr (pathname, '/'))
3530 internal_error (_("%s: restricted: cannot specify `/' in command names"),
3532 last_command_exit_value = EXECUTION_FAILURE;
3534 /* If we're not going to fork below, we must already be in a child
3535 process or a context in which it's safe to call exit(2). */
3536 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3537 exit (last_command_exit_value);
3541 #endif /* RESTRICTED_SHELL */
3543 command = search_for_command (pathname);
3547 maybe_make_export_env ();
3548 put_command_name_into_env (command);
3551 /* We have to make the child before we check for the non-existence
3552 of COMMAND, since we want the error messages to be redirected. */
3553 /* If we can get away without forking and there are no pipes to deal with,
3554 don't bother to fork, just directly exec the command. */
3555 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3558 pid = make_child (savestring (command_line), async);
3562 int old_interactive;
3565 /* This has been disabled for the time being. */
3566 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3567 if (posixly_correct == 0)
3568 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
3572 /* Cancel traps, in trap.c. */
3573 restore_original_signals ();
3575 /* restore_original_signals may have undone the work done
3576 by make_child to ensure that SIGINT and SIGQUIT are ignored
3577 in asynchronous children. */
3580 if ((cmdflags & CMD_STDIN_REDIR) &&
3581 pipe_in == NO_PIPE &&
3582 (stdin_redirects (redirects) == 0))
3583 async_redirect_stdin ();
3584 setup_async_signals ();
3587 /* This functionality is now provided by close-on-exec of the
3588 file descriptors manipulated by redirection and piping.
3589 Some file descriptors still need to be closed in all children
3590 because of the way bash does pipes; fds_to_close is a
3591 bitmap of all such file descriptors. */
3593 close_fd_bitmap (fds_to_close);
3595 do_piping (pipe_in, pipe_out);
3597 old_interactive = interactive;
3601 subshell_environment = SUBSHELL_FORK;
3603 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
3605 #if defined (PROCESS_SUBSTITUTION)
3606 /* Try to remove named pipes that may have been created as the
3607 result of redirections. */
3608 unlink_fifo_list ();
3609 #endif /* PROCESS_SUBSTITUTION */
3610 exit (EXECUTION_FAILURE);
3614 interactive = old_interactive;
3618 internal_error (_("%s: command not found"), pathname);
3619 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3622 /* Execve expects the command name to be in args[0]. So we
3623 leave it there, in the same format that the user used to
3625 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
3626 exit (shell_execve (command, args, export_env));
3631 /* Make sure that the pipes are closed in the parent. */
3632 close_pipes (pipe_in, pipe_out);
3633 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3634 unlink_fifo_list ();
3640 /* CPP defines to decide whether a particular index into the #! line
3641 corresponds to a valid interpreter name or argument character, or
3642 whitespace. The MSDOS define is to allow \r to be treated the same
3645 #if !defined (MSDOS)
3646 # define STRINGCHAR(ind) \
3647 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
3648 # define WHITECHAR(ind) \
3649 (ind < sample_len && whitespace (sample[ind]))
3651 # define STRINGCHAR(ind) \
3652 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
3653 # define WHITECHAR(ind) \
3654 (ind < sample_len && whitespace (sample[ind]))
3658 getinterp (sample, sample_len, endp)
3660 int sample_len, *endp;
3666 /* Find the name of the interpreter to exec. */
3667 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
3670 for (start = i; STRINGCHAR(i); i++)
3673 execname = substring (sample, start, i);
3680 #if !defined (HAVE_HASH_BANG_EXEC)
3681 /* If the operating system on which we're running does not handle
3682 the #! executable format, then help out. SAMPLE is the text read
3683 from the file, SAMPLE_LEN characters. COMMAND is the name of
3684 the script; it and ARGS, the arguments given by the user, will
3685 become arguments to the specified interpreter. ENV is the environment
3686 to pass to the interpreter.
3688 The word immediately following the #! is the interpreter to execute.
3689 A single argument to the interpreter is allowed. */
3692 execute_shell_script (sample, sample_len, command, args, env)
3698 char *execname, *firstarg;
3699 int i, start, size_increment, larry;
3701 /* Find the name of the interpreter to exec. */
3702 execname = getinterp (sample, sample_len, &i);
3705 /* Now the argument, if any. */
3706 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
3709 /* If there is more text on the line, then it is an argument for the
3714 for (start = i; STRINGCHAR(i); i++)
3716 firstarg = substring ((char *)sample, start, i);
3720 larry = strvec_len (args) + size_increment;
3721 args = strvec_resize (args, larry + 1);
3723 for (i = larry - 1; i; i--)
3724 args[i] = args[i - size_increment];
3735 args[larry] = (char *)NULL;
3737 return (shell_execve (execname, args, env));
3742 #endif /* !HAVE_HASH_BANG_EXEC */
3745 initialize_subshell ()
3748 /* Forget about any aliases that we knew of. We are in a subshell. */
3749 delete_all_aliases ();
3752 #if defined (HISTORY)
3753 /* Forget about the history lines we have read. This is a non-interactive
3755 history_lines_this_session = 0;
3758 #if defined (JOB_CONTROL)
3759 /* Forget about the way job control was working. We are in a subshell. */
3760 without_job_control ();
3761 set_sigchld_handler ();
3762 #endif /* JOB_CONTROL */
3764 /* Reset the values of the shell flags and options. */
3765 reset_shell_flags ();
3766 reset_shell_options ();
3767 reset_shopt_options ();
3769 /* Zero out builtin_env, since this could be a shell script run from a
3770 sourced file with a temporary environment supplied to the `source/.'
3771 builtin. Such variables are not supposed to be exported (empirical
3772 testing with sh and ksh). Just throw it away; don't worry about a
3774 if (vc_isbltnenv (shell_variables))
3775 shell_variables = shell_variables->down;
3777 clear_unwind_protect_list (0);
3779 /* We're no longer inside a shell function. */
3780 variable_context = return_catch_flag = 0;
3782 /* If we're not interactive, close the file descriptor from which we're
3783 reading the current shell script. */
3784 if (interactive_shell == 0)
3785 unset_bash_input (0);
3788 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3789 # define SETOSTYPE(x) __setostype(x)
3791 # define SETOSTYPE(x)
3794 #define READ_SAMPLE_BUF(file, buf, len) \
3797 fd = open(file, O_RDONLY); \
3800 len = read (fd, buf, 80); \
3808 /* Call execve (), handling interpreting shell scripts, and handling
3811 shell_execve (command, args, env)
3820 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3821 execve (command, args, env);
3822 i = errno; /* error from execve() */
3825 /* If we get to this point, then start checking out the file.
3826 Maybe it is something we can hack ourselves. */
3829 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3830 internal_error (_("%s: is a directory"), command);
3831 else if (executable_file (command) == 0)
3834 file_error (command);
3838 /* The file has the execute bits set, but the kernel refuses to
3839 run it for some reason. See why. */
3840 #if defined (HAVE_HASH_BANG_EXEC)
3841 READ_SAMPLE_BUF (command, sample, sample_len);
3842 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3846 interp = getinterp (sample, sample_len, (int *)NULL);
3848 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
3854 file_error (command);
3856 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3859 /* This file is executable.
3860 If it begins with #!, then help out people with losing operating
3861 systems. Otherwise, check to see if it is a binary file by seeing
3862 if the contents of the first line (or up to 80 characters) are in the
3863 ASCII set. If it's a text file, execute the contents as shell commands,
3864 otherwise return 126 (EX_BINARY_FILE). */
3865 READ_SAMPLE_BUF (command, sample, sample_len);
3867 if (sample_len == 0)
3868 return (EXECUTION_SUCCESS);
3870 /* Is this supposed to be an executable script?
3871 If so, the format of the line is "#! interpreter [argument]".
3872 A single argument is allowed. The BSD kernel restricts
3873 the length of the entire line to 32 characters (32 bytes
3874 being the size of the BSD exec header), but we allow 80
3878 #if !defined (HAVE_HASH_BANG_EXEC)
3879 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3880 return (execute_shell_script (sample, sample_len, command, args, env));
3883 if (check_binary_file (sample, sample_len))
3885 internal_error (_("%s: cannot execute binary file"), command);
3886 return (EX_BINARY_FILE);
3890 /* We have committed to attempting to execute the contents of this file
3891 as shell commands. */
3893 initialize_subshell ();
3895 set_sigint_handler ();
3897 /* Insert the name of this shell into the argument list. */
3898 larray = strvec_len (args) + 1;
3899 args = strvec_resize (args, larray + 1);
3901 for (i = larray - 1; i; i--)
3902 args[i] = args[i - 1];
3904 args[0] = shell_name;
3906 args[larray] = (char *)NULL;
3908 if (args[0][0] == '-')
3911 #if defined (RESTRICTED_SHELL)
3913 change_flag ('r', FLAG_OFF);
3918 /* Can't free subshell_argv[0]; that is shell_name. */
3919 for (i = 1; i < subshell_argc; i++)
3920 free (subshell_argv[i]);
3921 free (subshell_argv);
3924 dispose_command (currently_executing_command); /* XXX */
3925 currently_executing_command = (COMMAND *)NULL;
3927 subshell_argc = larray;
3928 subshell_argv = args;
3929 subshell_envp = env;
3931 unbind_args (); /* remove the positional parameters */
3933 longjmp (subshell_top_level, 1);
3938 execute_intern_function (name, function)
3944 if (check_identifier (name, posixly_correct) == 0)
3946 if (posixly_correct && interactive_shell == 0)
3948 last_command_exit_value = EX_USAGE;
3949 jump_to_top_level (ERREXIT);
3951 return (EXECUTION_FAILURE);
3954 var = find_function (name->word);
3955 if (var && (readonly_p (var) || noassign_p (var)))
3957 if (readonly_p (var))
3958 internal_error (_("%s: readonly function"), var->name);
3959 return (EXECUTION_FAILURE);
3962 bind_function (name->word, function);
3963 return (EXECUTION_SUCCESS);
3966 #if defined (INCLUDE_UNUSED)
3967 #if defined (PROCESS_SUBSTITUTION)
3971 register int i, fd_table_size;
3973 fd_table_size = getdtablesize ();
3974 if (fd_table_size > 256) /* clamp to a reasonable value */
3975 fd_table_size = 256;
3977 for (i = 3; i < fd_table_size; i++)
3980 #endif /* PROCESS_SUBSTITUTION */
3984 close_pipes (in, out)
3994 dup_error (oldd, newd)
3997 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
4000 /* Redirect input and output to be from and to the specified pipes.
4001 NO_PIPE and REDIRECT_BOTH are handled correctly. */
4003 do_piping (pipe_in, pipe_out)
4004 int pipe_in, pipe_out;
4006 if (pipe_in != NO_PIPE)
4008 if (dup2 (pipe_in, 0) < 0)
4009 dup_error (pipe_in, 0);
4013 if (pipe_out != NO_PIPE)
4015 if (pipe_out != REDIRECT_BOTH)
4017 if (dup2 (pipe_out, 1) < 0)
4018 dup_error (pipe_out, 1);
4019 if (pipe_out == 0 || pipe_out > 1)
4024 if (dup2 (1, 2) < 0)