1 /* execute_command.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987,1991 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
22 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #endif /* _AIX && RISC6000 && !__GNUC__ */
27 #include "chartypes.h"
28 #include "bashtypes.h"
30 # include <sys/file.h>
33 #include "posixstat.h"
36 # include <sys/param.h>
39 #if defined (HAVE_UNISTD_H)
43 #include "posixtime.h"
45 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
46 # include <sys/resource.h>
49 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
50 # include <sys/times.h>
63 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
68 #include "execute_cmd.h"
75 #if defined (COND_COMMAND)
79 #include "builtins/common.h"
80 #include "builtins/builtext.h" /* list of builtins */
82 #include <glob/strmatch.h>
83 #include <tilde/tilde.h>
85 #if defined (BUFFERED_INPUT)
94 # include "bashhist.h"
97 extern int posixly_correct;
98 extern int breaking, continuing, loop_level;
99 extern int expand_aliases;
100 extern int parse_and_execute_level, running_trap, trap_line_number;
101 extern int command_string_index, line_number;
102 extern int dot_found_in_search;
103 extern int already_making_children;
104 extern char **temporary_env, **function_env, **builtin_env;
105 extern char *the_printed_command, *shell_name;
106 extern pid_t last_command_subst_pid;
107 extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
108 extern char **subshell_argv, **subshell_envp;
109 extern int subshell_argc;
111 extern char *glob_argv_flags;
114 extern int close __P((int));
116 /* Static functions defined and used in this file. */
117 static void close_pipes __P((int, int));
118 static void do_piping __P((int, int));
119 static void bind_lastarg __P((char *));
120 static int shell_control_structure __P((enum command_type));
121 static void cleanup_redirects __P((REDIRECT *));
123 #if defined (JOB_CONTROL)
124 static int restore_signal_mask __P((sigset_t *));
127 static void async_redirect_stdin __P((void));
129 static int builtin_status __P((int));
131 static int execute_for_command __P((FOR_COM *));
132 #if defined (SELECT_COMMAND)
133 static int print_index_and_element __P((int, int, WORD_LIST *));
134 static void indent __P((int, int));
135 static void print_select_list __P((WORD_LIST *, int, int, int));
136 static char *select_query __P((WORD_LIST *, int, char *));
137 static int execute_select_command __P((SELECT_COM *));
139 #if defined (DPAREN_ARITHMETIC)
140 static int execute_arith_command __P((ARITH_COM *));
142 #if defined (COND_COMMAND)
143 static int execute_cond_node __P((COND_COM *));
144 static int execute_cond_command __P((COND_COM *));
146 #if defined (COMMAND_TIMING)
147 static int mkfmt __P((char *, int, int, time_t, int));
148 static void print_formatted_time __P((FILE *, char *,
149 time_t, int, time_t, int,
151 static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
153 #if defined (ARITH_FOR_COMMAND)
154 static long eval_arith_for_expr __P((WORD_LIST *, int *));
155 static int execute_arith_for_command __P((ARITH_FOR_COM *));
157 static int execute_case_command __P((CASE_COM *));
158 static int execute_while_command __P((WHILE_COM *));
159 static int execute_until_command __P((WHILE_COM *));
160 static int execute_while_or_until __P((WHILE_COM *, int));
161 static int execute_if_command __P((IF_COM *));
162 static int execute_null_command __P((REDIRECT *, int, int, int, pid_t));
163 static void fix_assignment_words __P((WORD_LIST *));
164 static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
165 static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
166 static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
167 static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
169 REDIRECT *, struct fd_bitmap *, int));
170 static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
176 static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
177 int, int, int, struct fd_bitmap *, int));
179 static char *getinterp __P((char *, int, int *));
180 static void initialize_subshell __P((void));
181 static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
183 static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
185 static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
187 static int execute_intern_function __P((WORD_DESC *, COMMAND *));
191 /* The line number that the currently executing function starts on. */
192 static int function_line_number;
194 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
195 so that reader_loop can set it to zero before executing a command. */
198 /* The name of the command that is currently being executed.
199 `test' needs this, for example. */
200 char *this_command_name;
202 static COMMAND *currently_executing_command;
204 struct stat SB; /* used for debugging */
206 static int special_builtin_failed;
208 /* For catching RETURN in a function. */
209 int return_catch_flag;
210 int return_catch_value;
211 procenv_t return_catch;
213 /* The value returned by the last synchronous command. */
214 int last_command_exit_value;
216 /* The list of redirections to perform which will undo the redirections
217 that I made in the shell. */
218 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
220 /* The list of redirections to perform which will undo the internal
221 redirections performed by the `exec' builtin. These are redirections
222 that must be undone even when exec discards redirection_undo_list. */
223 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
225 /* Non-zero if we have just forked and are currently running in a subshell
227 int subshell_environment;
229 /* Currently-executing shell function. */
230 SHELL_VAR *this_shell_function;
232 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
234 #define FD_BITMAP_DEFAULT_SIZE 32
236 /* Functions to allocate and deallocate the structures used to pass
237 information from the shell to its children about file descriptors
243 struct fd_bitmap *ret;
245 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
251 ret->bitmap = (char *)xmalloc (size);
252 bzero (ret->bitmap, size);
255 ret->bitmap = (char *)NULL;
260 dispose_fd_bitmap (fdbp)
261 struct fd_bitmap *fdbp;
268 close_fd_bitmap (fdbp)
269 struct fd_bitmap *fdbp;
275 for (i = 0; i < fdbp->size; i++)
284 /* Return the line number of the currently executing command. */
286 executing_line_number ()
288 if (executing && variable_context == 0 && currently_executing_command &&
289 currently_executing_command->type == cm_simple)
290 return currently_executing_command->value.Simple->line;
291 else if (running_trap)
292 return trap_line_number;
297 /* Execute the command passed in COMMAND. COMMAND is exactly what
298 read_command () places into GLOBAL_COMMAND. See "command.h" for the
299 details of the command structure.
301 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
302 return values. Executing a command with nothing in it returns
303 EXECUTION_SUCCESS. */
305 execute_command (command)
308 struct fd_bitmap *bitmap;
311 current_fds_to_close = (struct fd_bitmap *)NULL;
312 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
313 begin_unwind_frame ("execute-command");
314 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
316 /* Just do the command, but not asynchronously. */
317 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
319 dispose_fd_bitmap (bitmap);
320 discard_unwind_frame ("execute-command");
322 #if defined (PROCESS_SUBSTITUTION)
323 /* don't unlink fifos if we're in a shell function; wait until the function
325 if (variable_context == 0)
327 #endif /* PROCESS_SUBSTITUTION */
332 /* Return 1 if TYPE is a shell control structure type. */
334 shell_control_structure (type)
335 enum command_type type;
340 #if defined (ARITH_FOR_COMMAND)
343 #if defined (SELECT_COMMAND)
346 #if defined (DPAREN_ARITHMETIC)
349 #if defined (COND_COMMAND)
364 /* A function to use to unwind_protect the redirection undo list
367 cleanup_redirects (list)
370 do_redirections (list, 1, 0, 0);
371 dispose_redirects (list);
375 /* Function to unwind_protect the redirections for functions and builtins. */
377 cleanup_func_redirects (list)
380 do_redirections (list, 1, 0, 0);
385 dispose_exec_redirects ()
387 if (exec_redirection_undo_list)
389 dispose_redirects (exec_redirection_undo_list);
390 exec_redirection_undo_list = (REDIRECT *)NULL;
394 #if defined (JOB_CONTROL)
395 /* A function to restore the signal mask to its proper value when the shell
396 is interrupted or errors occur while creating a pipeline. */
398 restore_signal_mask (set)
401 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
403 #endif /* JOB_CONTROL */
406 /* A debugging function that can be called from gdb, for instance. */
411 int f, fd_table_size;
413 fd_table_size = getdtablesize ();
415 fprintf (stderr, "pid %ld open files:", (long)getpid ());
416 for (i = 3; i < fd_table_size; i++)
418 if ((f = fcntl (i, F_GETFD, 0)) != -1)
419 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
421 fprintf (stderr, "\n");
426 async_redirect_stdin ()
430 fd = open ("/dev/null", O_RDONLY);
437 internal_error ("cannot redirect standard input from /dev/null: %s", strerror (errno));
440 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
442 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
443 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
444 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
445 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
446 from and where it goes. They can have the value of NO_PIPE, which means
448 FDS_TO_CLOSE is a list of file descriptors to close once the child has
449 been forked. This list often contains the unusable sides of pipes, etc.
451 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
452 return values. Executing a command with nothing in it returns
453 EXECUTION_SUCCESS. */
455 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
459 int pipe_in, pipe_out;
460 struct fd_bitmap *fds_to_close;
462 int exec_result, invert, ignore_return, was_debug_trap, was_error_trap;
463 REDIRECT *my_undo_list, *exec_undo_list;
464 volatile pid_t last_pid;
466 if (command == 0 || breaking || continuing || read_but_dont_execute)
467 return (EXECUTION_SUCCESS);
469 run_pending_traps ();
471 if (running_trap == 0)
472 currently_executing_command = command;
474 invert = (command->flags & CMD_INVERT_RETURN) != 0;
476 /* If we're inverting the return value and `set -e' has been executed,
477 we don't want a failing command to inadvertently cause the shell
479 if (exit_immediately_on_error && invert) /* XXX */
480 command->flags |= CMD_IGNORE_RETURN; /* XXX */
482 exec_result = EXECUTION_SUCCESS;
484 /* If a command was being explicitly run in a subshell, or if it is
485 a shell control-structure, and it has a pipe, then we do the command
487 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
488 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
490 if (command->type == cm_subshell ||
491 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
492 (shell_control_structure (command->type) &&
493 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
497 /* Fork a subshell, turn off the subshell bit, turn off job
498 control and call execute_command () on the command again. */
499 paren_pid = make_child (savestring (make_command_string (command)),
502 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
506 close_pipes (pipe_in, pipe_out);
508 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
511 /* If we are part of a pipeline, and not the end of the pipeline,
512 then we should simply return and let the last command in the
513 pipe be waited for. If we are not in a pipeline, or are the
514 last command in the pipeline, then we wait for the subshell
515 and return its exit status as usual. */
516 if (pipe_out != NO_PIPE)
517 return (EXECUTION_SUCCESS);
519 stop_pipeline (asynchronous, (COMMAND *)NULL);
521 if (asynchronous == 0)
523 last_command_exit_value = wait_for (paren_pid);
525 /* If we have to, invert the return value. */
527 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
529 : EXECUTION_SUCCESS);
531 exec_result = last_command_exit_value;
533 return (last_command_exit_value = exec_result);
537 DESCRIBE_PID (paren_pid);
539 run_pending_traps ();
541 return (EXECUTION_SUCCESS);
546 #if defined (COMMAND_TIMING)
547 if (command->flags & CMD_TIME_PIPELINE)
551 command->flags |= CMD_FORCE_SUBSHELL;
552 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
556 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
557 if (running_trap == 0)
558 currently_executing_command = (COMMAND *)NULL;
560 return (exec_result);
562 #endif /* COMMAND_TIMING */
564 if (shell_control_structure (command->type) && command->redirects)
565 stdin_redir = stdin_redirects (command->redirects);
567 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
569 if (do_redirections (command->redirects, 1, 1, 0) != 0)
571 cleanup_redirects (redirection_undo_list);
572 redirection_undo_list = (REDIRECT *)NULL;
573 dispose_exec_redirects ();
574 return (EXECUTION_FAILURE);
577 if (redirection_undo_list)
579 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
580 dispose_redirects (redirection_undo_list);
581 redirection_undo_list = (REDIRECT *)NULL;
584 my_undo_list = (REDIRECT *)NULL;
586 if (exec_redirection_undo_list)
588 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
589 dispose_redirects (exec_redirection_undo_list);
590 exec_redirection_undo_list = (REDIRECT *)NULL;
593 exec_undo_list = (REDIRECT *)NULL;
595 if (my_undo_list || exec_undo_list)
596 begin_unwind_frame ("loop_redirections");
599 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
602 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
604 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
608 switch (command->type)
612 /* We can't rely on this variable retaining its value across a
613 call to execute_simple_command if a longjmp occurs as the
614 result of a `return' builtin. This is true for sure with gcc. */
615 last_pid = last_made_pid;
616 was_debug_trap = signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0;
617 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
619 if (ignore_return && command->value.Simple)
620 command->value.Simple->flags |= CMD_IGNORE_RETURN;
621 if (command->flags & CMD_STDIN_REDIR)
622 command->value.Simple->flags |= CMD_STDIN_REDIR;
624 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
625 asynchronous, fds_to_close);
627 /* The temporary environment should be used for only the simple
628 command immediately following its definition. */
629 dispose_used_env_vars ();
631 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
632 /* Reclaim memory allocated with alloca () on machines which
633 may be using the alloca emulation code. */
635 #endif /* (ultrix && mips) || C_ALLOCA */
637 /* If we forked to do the command, then we must wait_for ()
640 /* XXX - this is something to watch out for if there are problems
641 when the shell is compiled without job control. */
642 if (already_making_children && pipe_out == NO_PIPE &&
643 last_pid != last_made_pid)
645 stop_pipeline (asynchronous, (COMMAND *)NULL);
649 DESCRIBE_PID (last_made_pid);
652 #if !defined (JOB_CONTROL)
653 /* Do not wait for asynchronous processes started from
655 if (last_made_pid != last_asynchronous_pid)
657 /* When executing a shell function that executes other
658 commands, this causes the last simple command in
659 the function to be waited for twice. */
660 exec_result = wait_for (last_made_pid);
661 #if defined (RECYCLES_PIDS)
662 /* LynxOS, for one, recycles pids very quickly -- so quickly
663 that a new process may have the same pid as the last one
664 created. This has been reported to fix the problem. */
665 if (exec_result == 0)
666 last_made_pid = NO_PID;
673 last_command_exit_value = exec_result;
677 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
679 last_command_exit_value = exec_result;
683 if (ignore_return == 0 && invert == 0 &&
684 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
685 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
687 last_command_exit_value = exec_result;
688 run_pending_traps ();
689 jump_to_top_level (EXITPROG);
696 command->value.For->flags |= CMD_IGNORE_RETURN;
697 exec_result = execute_for_command (command->value.For);
700 #if defined (ARITH_FOR_COMMAND)
703 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
704 exec_result = execute_arith_for_command (command->value.ArithFor);
708 #if defined (SELECT_COMMAND)
711 command->value.Select->flags |= CMD_IGNORE_RETURN;
712 exec_result = execute_select_command (command->value.Select);
718 command->value.Case->flags |= CMD_IGNORE_RETURN;
719 exec_result = execute_case_command (command->value.Case);
724 command->value.While->flags |= CMD_IGNORE_RETURN;
725 exec_result = execute_while_command (command->value.While);
730 command->value.While->flags |= CMD_IGNORE_RETURN;
731 exec_result = execute_until_command (command->value.While);
736 command->value.If->flags |= CMD_IGNORE_RETURN;
737 exec_result = execute_if_command (command->value.If);
742 /* This code can be executed from either of two paths: an explicit
743 '{}' command, or via a function call. If we are executed via a
744 function call, we have already taken care of the function being
745 executed in the background (down there in execute_simple_command ()),
746 and this command should *not* be marked as asynchronous. If we
747 are executing a regular '{}' group command, and asynchronous == 1,
748 we must want to execute the whole command in the background, so we
749 need a subshell, and we want the stuff executed in that subshell
750 (this group command) to be executed in the foreground of that
751 subshell (i.e. there will not be *another* subshell forked).
753 What we do is to force a subshell if asynchronous, and then call
754 execute_command_internal again with asynchronous still set to 1,
755 but with the original group command, so the printed command will
758 The code above that handles forking off subshells will note that
759 both subshell and async are on, and turn off async in the child
760 after forking the subshell (but leave async set in the parent, so
761 the normal call to describe_pid is made). This turning off
762 async is *crucial*; if it is not done, this will fall into an
763 infinite loop of executions through this spot in subshell after
764 subshell until the process limit is exhausted. */
768 command->flags |= CMD_FORCE_SUBSHELL;
770 execute_command_internal (command, 1, pipe_in, pipe_out,
775 if (ignore_return && command->value.Group->command)
776 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
778 execute_command_internal (command->value.Group->command,
779 asynchronous, pipe_in, pipe_out,
785 exec_result = execute_connection (command, asynchronous,
786 pipe_in, pipe_out, fds_to_close);
789 #if defined (DPAREN_ARITHMETIC)
792 command->value.Arith->flags |= CMD_IGNORE_RETURN;
793 exec_result = execute_arith_command (command->value.Arith);
797 #if defined (COND_COMMAND)
800 command->value.Cond->flags |= CMD_IGNORE_RETURN;
801 exec_result = execute_cond_command (command->value.Cond);
805 case cm_function_def:
806 exec_result = execute_intern_function (command->value.Function_def->name,
807 command->value.Function_def->command);
811 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
816 do_redirections (my_undo_list, 1, 0, 0);
817 dispose_redirects (my_undo_list);
821 dispose_redirects (exec_undo_list);
823 if (my_undo_list || exec_undo_list)
824 discard_unwind_frame ("loop_redirections");
826 /* Invert the return value if we have to */
828 exec_result = (exec_result == EXECUTION_SUCCESS)
832 last_command_exit_value = exec_result;
833 run_pending_traps ();
834 if (running_trap == 0)
835 currently_executing_command = (COMMAND *)NULL;
836 return (last_command_exit_value);
839 #if defined (COMMAND_TIMING)
841 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
842 extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
843 extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
844 extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
847 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
848 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
850 static int precs[] = { 0, 100, 10, 1 };
852 /* Expand one `%'-prefixed escape sequence from a time format string. */
854 mkfmt (buf, prec, lng, sec, sec_fraction)
861 char abuf[INT_STRLEN_BOUND(time_t) + 1];
865 abuf[sizeof(abuf) - 1] = '\0';
867 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
872 aind = sizeof(abuf) - 2;
874 abuf[aind--] = (min % 10) + '0';
878 buf[ind++] = abuf[aind++];
882 /* Now add the seconds. */
883 aind = sizeof (abuf) - 2;
885 abuf[aind--] = (sec % 10) + '0';
889 buf[ind++] = abuf[aind++];
891 /* We want to add a decimal point and PREC places after it if PREC is
892 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
897 for (aind = 1; aind <= prec; aind++)
899 buf[ind++] = (sec_fraction / precs[aind]) + '0';
900 sec_fraction %= precs[aind];
911 /* Interpret the format string FORMAT, interpolating the following escape
915 where the optional `prec' is a precision, meaning the number of
916 characters after the decimal point, the optional `l' means to format
917 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
918 and the last character is one of
920 R number of seconds of `real' time
921 U number of seconds of `user' time
922 S number of seconds of `system' time
924 An occurrence of `%%' in the format string is translated to a `%'. The
925 result is printed to FP, a pointer to a FILE. The other variables are
926 the seconds and thousandths of a second of real, user, and system time,
929 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
940 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
945 len = strlen (format);
946 ssize = (len + 64) - (len % 64);
947 str = (char *)xmalloc (ssize);
950 for (s = format; *s; s++)
952 if (*s != '%' || s[1] == '\0')
954 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
957 else if (s[1] == '%')
960 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
963 else if (s[1] == 'P')
969 sum_frac = (cpu % 100) * 10;
970 len = mkfmt (ts, 2, 0, sum, sum_frac);
971 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
972 strcpy (str + sindex, ts);
977 prec = 3; /* default is three places past the decimal point. */
978 lng = 0; /* default is to not use minutes or append `s' */
980 if (DIGIT (*s)) /* `precision' */
983 if (prec > 3) prec = 3;
985 if (*s == 'l') /* `length extender' */
990 if (*s == 'R' || *s == 'E')
991 len = mkfmt (ts, prec, lng, rs, rsf);
993 len = mkfmt (ts, prec, lng, us, usf);
995 len = mkfmt (ts, prec, lng, ss, ssf);
998 internal_error ("bad format character in time format: %c", *s);
1002 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1003 strcpy (str + sindex, ts);
1009 fprintf (fp, "%s\n", str);
1016 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1018 int asynchronous, pipe_in, pipe_out;
1019 struct fd_bitmap *fds_to_close;
1021 int rv, posix_time, old_flags;
1027 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1028 struct timeval real, user, sys;
1029 struct timeval before, after;
1030 struct timezone dtz;
1031 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1033 # if defined (HAVE_TIMES)
1034 clock_t tbefore, tafter, real, user, sys;
1035 struct tms before, after;
1039 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1040 gettimeofday (&before, &dtz);
1041 getrusage (RUSAGE_SELF, &selfb);
1042 getrusage (RUSAGE_CHILDREN, &kidsb);
1044 # if defined (HAVE_TIMES)
1045 tbefore = times (&before);
1049 posix_time = (command->flags & CMD_TIME_POSIX);
1051 old_flags = command->flags;
1052 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1053 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1054 command->flags = old_flags;
1057 rsf = usf = ssf = cpu = 0;
1059 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1060 gettimeofday (&after, &dtz);
1061 getrusage (RUSAGE_SELF, &selfa);
1062 getrusage (RUSAGE_CHILDREN, &kidsa);
1064 difftimeval (&real, &before, &after);
1065 timeval_to_secs (&real, &rs, &rsf);
1067 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1068 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1069 timeval_to_secs (&user, &us, &usf);
1071 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1072 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1073 timeval_to_secs (&sys, &ss, &ssf);
1075 cpu = timeval_to_cpu (&real, &user, &sys);
1077 # if defined (HAVE_TIMES)
1078 tafter = times (&after);
1080 real = tafter - tbefore;
1081 clock_t_to_secs (real, &rs, &rsf);
1083 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1084 clock_t_to_secs (user, &us, &usf);
1086 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1087 clock_t_to_secs (sys, &ss, &ssf);
1089 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1093 rsf = usf = ssf = cpu = 0;
1098 time_format = POSIX_TIMEFORMAT;
1099 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1100 time_format = BASH_TIMEFORMAT;
1102 if (time_format && *time_format)
1103 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1107 #endif /* COMMAND_TIMING */
1109 /* Execute a command that's supposed to be in a subshell. This must be
1110 called after make_child and we must be running in the child process.
1111 The caller will return or exit() immediately with the value this returns. */
1113 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1116 int pipe_in, pipe_out;
1117 struct fd_bitmap *fds_to_close;
1119 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1123 USE_VAR(user_subshell);
1126 USE_VAR(asynchronous);
1128 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1129 pipe_in == NO_PIPE &&
1130 stdin_redirects (command->redirects) == 0);
1132 invert = (command->flags & CMD_INVERT_RETURN) != 0;
1133 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1135 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1137 /* If a command is asynchronous in a subshell (like ( foo ) & or
1138 the special case of an asynchronous GROUP command where the
1139 the subshell bit is turned on down in case cm_group: below),
1140 turn off `asynchronous', so that two subshells aren't spawned.
1142 This seems semantically correct to me. For example,
1143 ( foo ) & seems to say ``do the command `foo' in a subshell
1144 environment, but don't wait for that subshell to finish'',
1145 and "{ foo ; bar ; } &" seems to me to be like functions or
1146 builtins in the background, which executed in a subshell
1147 environment. I just don't see the need to fork two subshells. */
1149 /* Don't fork again, we are already in a subshell. A `doubly
1150 async' shell is not interactive, however. */
1153 #if defined (JOB_CONTROL)
1154 /* If a construct like ( exec xxx yyy ) & is given while job
1155 control is active, we want to prevent exec from putting the
1156 subshell back into the original process group, carefully
1157 undoing all the work we just did in make_child. */
1159 #endif /* JOB_CONTROL */
1160 ois = interactive_shell;
1161 interactive_shell = 0;
1162 /* This test is to prevent alias expansion by interactive shells that
1163 run `(command) &' but to allow scripts that have enabled alias
1164 expansion with `shopt -s expand_alias' to continue to expand
1166 if (ois != interactive_shell)
1171 /* Subshells are neither login nor interactive. */
1172 login_shell = interactive = 0;
1174 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
1176 reset_terminating_signals (); /* in sig.c */
1177 /* Cancel traps, in trap.c. */
1178 restore_original_signals ();
1180 setup_async_signals ();
1182 #if defined (JOB_CONTROL)
1183 set_sigchld_handler ();
1184 #endif /* JOB_CONTROL */
1186 set_sigint_handler ();
1188 #if defined (JOB_CONTROL)
1189 /* Delete all traces that there were any jobs running. This is
1190 only for subshells. */
1191 without_job_control ();
1192 #endif /* JOB_CONTROL */
1195 close_fd_bitmap (fds_to_close);
1197 do_piping (pipe_in, pipe_out);
1199 /* If this is a user subshell, set a flag if stdin was redirected.
1200 This is used later to decide whether to redirect fd 0 to
1201 /dev/null for async commands in the subshell. This adds more
1202 sh compatibility, but I'm not sure it's the right thing to do. */
1205 stdin_redir = stdin_redirects (command->redirects);
1206 restore_default_signal (0);
1209 /* If this is an asynchronous command (command &), we want to
1210 redirect the standard input from /dev/null in the absence of
1211 any specific redirection involving stdin. */
1212 if (should_redir_stdin && stdin_redir == 0)
1213 async_redirect_stdin ();
1215 /* Do redirections, then dispose of them before recursive call. */
1216 if (command->redirects)
1218 if (do_redirections (command->redirects, 1, 0, 0) != 0)
1219 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1221 dispose_redirects (command->redirects);
1222 command->redirects = (REDIRECT *)NULL;
1225 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1227 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1228 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1229 tcom->flags |= CMD_IGNORE_RETURN;
1231 /* If this is a simple command, tell execute_disk_command that it
1232 might be able to get away without forking and simply exec.
1233 This means things like ( sleep 10 ) will only cause one fork.
1234 If we're timing the command or inverting its return value, however,
1235 we cannot do this optimization. */
1236 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1237 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1238 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1240 tcom->flags |= CMD_NO_FORK;
1241 if (tcom->type == cm_simple)
1242 tcom->value.Simple->flags |= CMD_NO_FORK;
1245 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1246 tcom->flags &= ~CMD_INVERT_RETURN;
1248 /* If we're inside a function while executing this subshell, we
1249 need to handle a possible `return'. */
1251 if (return_catch_flag)
1252 function_value = setjmp (return_catch);
1255 return_code = return_catch_value;
1257 return_code = execute_command_internal
1258 (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1260 /* If we are asked to, invert the return value. */
1262 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1263 : EXECUTION_SUCCESS;
1265 /* If we were explicitly placed in a subshell with (), we need
1266 to do the `shell cleanup' things, such as running traps[0]. */
1267 if (user_subshell && signal_is_trapped (0))
1269 last_command_exit_value = return_code;
1270 return_code = run_exit_trap ();
1273 return (return_code);
1278 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1280 int asynchronous, pipe_in, pipe_out;
1281 struct fd_bitmap *fds_to_close;
1283 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1285 struct fd_bitmap *fd_bitmap;
1287 #if defined (JOB_CONTROL)
1289 BLOCK_CHILD (set, oset);
1290 #endif /* JOB_CONTROL */
1292 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1297 while (cmd && cmd->type == cm_connection &&
1298 cmd->value.Connection && cmd->value.Connection->connector == '|')
1300 /* Make a pipeline between the two commands. */
1301 if (pipe (fildes) < 0)
1303 sys_error ("pipe error");
1304 #if defined (JOB_CONTROL)
1305 terminate_current_pipeline ();
1306 kill_current_pipeline ();
1307 #endif /* JOB_CONTROL */
1308 last_command_exit_value = EXECUTION_FAILURE;
1309 /* The unwind-protects installed below will take care
1310 of closing all of the open file descriptors. */
1311 throw_to_top_level ();
1312 return (EXECUTION_FAILURE); /* XXX */
1315 /* Here is a problem: with the new file close-on-exec
1316 code, the read end of the pipe (fildes[0]) stays open
1317 in the first process, so that process will never get a
1318 SIGPIPE. There is no way to signal the first process
1319 that it should close fildes[0] after forking, so it
1320 remains open. No SIGPIPE is ever sent because there
1321 is still a file descriptor open for reading connected
1322 to the pipe. We take care of that here. This passes
1323 around a bitmap of file descriptors that must be
1324 closed after making a child process in execute_simple_command. */
1326 /* We need fd_bitmap to be at least as big as fildes[0].
1327 If fildes[0] is less than fds_to_close->size, then
1328 use fds_to_close->size. */
1329 new_bitmap_size = (fildes[0] < fds_to_close->size)
1330 ? fds_to_close->size
1333 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1335 /* Now copy the old information into the new bitmap. */
1336 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1338 /* And mark the pipe file descriptors to be closed. */
1339 fd_bitmap->bitmap[fildes[0]] = 1;
1341 /* In case there are pipe or out-of-processes errors, we
1342 want all these file descriptors to be closed when
1343 unwind-protects are run, and the storage used for the
1344 bitmaps freed up. */
1345 begin_unwind_frame ("pipe-file-descriptors");
1346 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1347 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1349 add_unwind_protect (close, prev);
1350 dummyfd = fildes[1];
1351 add_unwind_protect (close, dummyfd);
1353 #if defined (JOB_CONTROL)
1354 add_unwind_protect (restore_signal_mask, &oset);
1355 #endif /* JOB_CONTROL */
1357 if (ignore_return && cmd->value.Connection->first)
1358 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1359 execute_command_internal (cmd->value.Connection->first, asynchronous,
1360 prev, fildes[1], fd_bitmap);
1368 dispose_fd_bitmap (fd_bitmap);
1369 discard_unwind_frame ("pipe-file-descriptors");
1371 cmd = cmd->value.Connection->second;
1374 /* Now execute the rightmost command in the pipeline. */
1375 if (ignore_return && cmd)
1376 cmd->flags |= CMD_IGNORE_RETURN;
1377 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1382 #if defined (JOB_CONTROL)
1383 UNBLOCK_CHILD (oset);
1386 return (exec_result);
1390 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1392 int asynchronous, pipe_in, pipe_out;
1393 struct fd_bitmap *fds_to_close;
1399 COMMAND *tc, *second;
1400 int ignore_return, exec_result;
1402 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1404 switch (command->value.Connection->connector)
1406 /* Do the first command asynchronously. */
1408 tc = command->value.Connection->first;
1410 return (EXECUTION_SUCCESS);
1415 tc->flags |= CMD_IGNORE_RETURN;
1416 tc->flags |= CMD_AMPERSAND;
1418 /* If this shell was compiled without job control support,
1419 if we are currently in a subshell via `( xxx )', or if job
1420 control is not active then the standard input for an
1421 asynchronous command is forced to /dev/null. */
1422 #if defined (JOB_CONTROL)
1423 if ((subshell_environment || !job_control) && !stdin_redir)
1426 #endif /* JOB_CONTROL */
1429 rd.filename = make_bare_word ("/dev/null");
1430 tr = make_redirection (0, r_inputa_direction, rd);
1431 tr->next = tc->redirects;
1434 tc->flags |= CMD_STDIN_REDIR;
1437 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1439 if (tc->flags & CMD_STDIN_REDIR)
1442 /* Remove the redirection we added above. It matters,
1443 especially for loops, which call execute_command ()
1444 multiple times with the same command. */
1449 tc->redirects = tc->redirects->next;
1451 while (tc->redirects && tc->redirects != rp);
1453 tl->next = (REDIRECT *)NULL;
1454 dispose_redirects (tr);
1456 tc->flags &= ~CMD_STDIN_REDIR;
1459 second = command->value.Connection->second;
1463 second->flags |= CMD_IGNORE_RETURN;
1465 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1470 /* Just call execute command on both sides. */
1474 if (command->value.Connection->first)
1475 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1476 if (command->value.Connection->second)
1477 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1480 execute_command (command->value.Connection->first);
1482 exec_result = execute_command_internal (command->value.Connection->second,
1483 asynchronous, pipe_in, pipe_out,
1488 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1495 /* If we have something like `a && b &' or `a || b &', run the
1496 && or || stuff in a subshell. Force a subshell and just call
1497 execute_command_internal again. Leave asynchronous on
1498 so that we get a report from the parent shell about the
1500 command->flags |= CMD_FORCE_SUBSHELL;
1501 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1505 /* Execute the first command. If the result of that is successful
1506 and the connector is AND_AND, or the result is not successful
1507 and the connector is OR_OR, then execute the second command,
1508 otherwise return. */
1510 if (command->value.Connection->first)
1511 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1513 exec_result = execute_command (command->value.Connection->first);
1515 if (((command->value.Connection->connector == AND_AND) &&
1516 (exec_result == EXECUTION_SUCCESS)) ||
1517 ((command->value.Connection->connector == OR_OR) &&
1518 (exec_result != EXECUTION_SUCCESS)))
1520 if (ignore_return && command->value.Connection->second)
1521 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1523 exec_result = execute_command (command->value.Connection->second);
1528 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
1529 jump_to_top_level (DISCARD);
1530 exec_result = EXECUTION_FAILURE;
1539 if (!interactive_shell) \
1540 reap_dead_jobs (); \
1544 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1547 execute_for_command (for_command)
1548 FOR_COM *for_command;
1550 register WORD_LIST *releaser, *list;
1555 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1558 if (check_identifier (for_command->name, 1) == 0)
1560 if (posixly_correct && interactive_shell == 0)
1562 last_command_exit_value = EX_USAGE;
1563 jump_to_top_level (EXITPROG);
1565 return (EXECUTION_FAILURE);
1569 identifier = for_command->name->word;
1571 list = releaser = expand_words_no_vars (for_command->map_list);
1573 begin_unwind_frame ("for");
1574 add_unwind_protect (dispose_words, releaser);
1577 if (lexical_scoping)
1579 old_value = copy_variable (find_variable (identifier));
1581 add_unwind_protect (dispose_variable, old_value);
1585 if (for_command->flags & CMD_IGNORE_RETURN)
1586 for_command->action->flags |= CMD_IGNORE_RETURN;
1588 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1591 this_command_name = (char *)NULL;
1592 v = bind_variable (identifier, list->word->word);
1593 if (readonly_p (v) || noassign_p (v))
1595 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1597 last_command_exit_value = EXECUTION_FAILURE;
1598 jump_to_top_level (FORCE_EOF);
1602 run_unwind_frame ("for");
1604 return (EXECUTION_FAILURE);
1607 retval = execute_command (for_command->action);
1628 if (lexical_scoping)
1631 makunbound (identifier, shell_variables);
1634 SHELL_VAR *new_value;
1636 new_value = bind_variable (identifier, value_cell(old_value));
1637 new_value->attributes = old_value->attributes;
1638 dispose_variable (old_value);
1643 dispose_words (releaser);
1644 discard_unwind_frame ("for");
1648 #if defined (ARITH_FOR_COMMAND)
1649 /* Execute an arithmetic for command. The syntax is
1651 for (( init ; step ; test ))
1656 The execution should be exactly equivalent to
1659 while eval \(\( test \)\) ; do
1665 eval_arith_for_expr (l, okp)
1672 new = expand_words_no_vars (l);
1675 if (echo_command_at_execute)
1676 xtrace_print_arith_cmd (new);
1677 expresult = evalexp (new->word->word, okp);
1678 dispose_words (new);
1690 execute_arith_for_command (arith_for_command)
1691 ARITH_FOR_COM *arith_for_command;
1694 int expok, body_status;
1696 body_status = EXECUTION_SUCCESS;
1699 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1700 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1702 this_command_name = "(("; /* )) for expression error messages */
1704 if (variable_context)
1705 line_number = arith_for_command->line - function_line_number;
1707 /* Evaluate the initialization expression. */
1708 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1710 return (EXECUTION_FAILURE);
1714 /* Evaluate the test expression. */
1715 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
1718 body_status = EXECUTION_FAILURE;
1725 /* Execute the body of the arithmetic for command. */
1727 body_status = execute_command (arith_for_command->action);
1730 /* Handle any `break' or `continue' commands executed by the body. */
1744 /* Evaluate the step expression. */
1745 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
1748 body_status = EXECUTION_FAILURE;
1754 return (body_status);
1758 #if defined (SELECT_COMMAND)
1759 static int LINES, COLS, tabsize;
1761 #define RP_SPACE ") "
1762 #define RP_SPACE_LEN 2
1764 /* XXX - does not handle numbers > 1000000 at all. */
1765 #define NUMBER_LEN(s) \
1769 : ((s < 10000) ? 4 \
1770 : ((s < 100000) ? 5 \
1774 print_index_and_element (len, ind, list)
1778 register WORD_LIST *l;
1783 for (i = ind, l = list; l && --i; l = l->next)
1785 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1786 return (STRLEN (l->word->word));
1795 if ((to / tabsize) > (from / tabsize))
1797 putc ('\t', stderr);
1798 from += tabsize - from % tabsize;
1809 print_select_list (list, list_len, max_elem_len, indices_len)
1811 int list_len, max_elem_len, indices_len;
1813 int ind, row, elem_len, pos, cols, rows;
1814 int first_column_indices_len, other_indices_len;
1818 putc ('\n', stderr);
1822 cols = max_elem_len ? COLS / max_elem_len : 1;
1825 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1826 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1834 first_column_indices_len = NUMBER_LEN (rows);
1835 other_indices_len = indices_len;
1837 for (row = 0; row < rows; row++)
1843 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1844 elem_len = print_index_and_element (indices_len, ind + 1, list);
1845 elem_len += indices_len + RP_SPACE_LEN;
1847 if (ind >= list_len)
1849 indent (pos + elem_len, pos + max_elem_len);
1850 pos += max_elem_len;
1852 putc ('\n', stderr);
1856 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1857 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1858 If the number is between 1 and LIST_LEN, return that selection. If EOF
1859 is read, return a null string. If a blank line is entered, or an invalid
1860 number is entered, the loop is executed again. */
1862 select_query (list, list_len, prompt)
1867 int max_elem_len, indices_len, len;
1870 char *repl_string, *t;
1872 t = get_string_value ("LINES");
1873 LINES = (t && *t) ? atoi (t) : 24;
1874 t = get_string_value ("COLUMNS");
1875 COLS = (t && *t) ? atoi (t) : 80;
1878 t = get_string_value ("TABSIZE");
1879 tabsize = (t && *t) ? atoi (t) : 8;
1887 for (l = list; l; l = l->next)
1889 len = STRLEN (l->word->word);
1890 if (len > max_elem_len)
1893 indices_len = NUMBER_LEN (list_len);
1894 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1898 print_select_list (list, list_len, max_elem_len, indices_len);
1899 fprintf (stderr, "%s", prompt);
1903 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1906 return ((char *)NULL);
1908 repl_string = get_string_value ("REPLY");
1909 if (*repl_string == 0)
1911 if (legal_number (repl_string, &reply) == 0)
1913 if (reply < 1 || reply > list_len)
1916 for (l = list; l && --reply; l = l->next)
1918 return (l->word->word);
1922 /* Execute a SELECT command. The syntax is:
1923 SELECT word IN list DO command_list DONE
1924 Only `break' or `return' in command_list will terminate
1927 execute_select_command (select_command)
1928 SELECT_COM *select_command;
1930 WORD_LIST *releaser, *list;
1932 char *identifier, *ps3_prompt, *selection;
1933 int retval, list_len;
1935 if (check_identifier (select_command->name, 1) == 0)
1936 return (EXECUTION_FAILURE);
1939 identifier = select_command->name->word;
1941 /* command and arithmetic substitution, parameter and variable expansion,
1942 word splitting, pathname expansion, and quote removal. */
1943 list = releaser = expand_words_no_vars (select_command->map_list);
1944 list_len = list_length (list);
1945 if (list == 0 || list_len == 0)
1948 dispose_words (list);
1949 return (EXECUTION_SUCCESS);
1952 begin_unwind_frame ("select");
1953 add_unwind_protect (dispose_words, releaser);
1955 if (select_command->flags & CMD_IGNORE_RETURN)
1956 select_command->action->flags |= CMD_IGNORE_RETURN;
1958 retval = EXECUTION_SUCCESS;
1962 ps3_prompt = get_string_value ("PS3");
1963 if (ps3_prompt == 0)
1967 selection = select_query (list, list_len, ps3_prompt);
1972 v = bind_variable (identifier, selection);
1973 if (readonly_p (v) || noassign_p (v))
1975 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
1977 last_command_exit_value = EXECUTION_FAILURE;
1978 jump_to_top_level (FORCE_EOF);
1982 run_unwind_frame ("select");
1983 return (EXECUTION_FAILURE);
1987 retval = execute_command (select_command->action);
2008 run_unwind_frame ("select");
2011 #endif /* SELECT_COMMAND */
2013 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2014 The pattern_list is a linked list of pattern clauses; each clause contains
2015 some patterns to compare word_desc against, and an associated command to
2018 execute_case_command (case_command)
2019 CASE_COM *case_command;
2021 register WORD_LIST *list;
2022 WORD_LIST *wlist, *es;
2023 PATTERN_LIST *clauses;
2024 char *word, *pattern;
2025 int retval, match, ignore_return;
2027 /* Posix.2 specifies that the WORD is tilde expanded. */
2028 if (member ('~', case_command->word->word))
2030 word = bash_tilde_expand (case_command->word->word);
2031 free (case_command->word->word);
2032 case_command->word->word = word;
2035 wlist = expand_word_unsplit (case_command->word, 0);
2036 word = wlist ? string_list (wlist) : savestring ("");
2037 dispose_words (wlist);
2039 retval = EXECUTION_SUCCESS;
2040 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
2042 begin_unwind_frame ("case");
2043 add_unwind_protect ((Function *)xfree, word);
2045 #define EXIT_CASE() goto exit_case_command
2047 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
2050 for (list = clauses->patterns; list; list = list->next)
2052 /* Posix.2 specifies to tilde expand each member of the pattern
2054 if (member ('~', list->word->word))
2056 pattern = bash_tilde_expand (list->word->word);
2057 free (list->word->word);
2058 list->word->word = pattern;
2061 es = expand_word_leave_quoted (list->word, 0);
2063 if (es && es->word && es->word->word && *(es->word->word))
2064 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
2067 pattern = (char *)xmalloc (1);
2071 /* Since the pattern does not undergo quote removal (as per
2072 Posix.2, section 3.9.4.3), the strmatch () call must be able
2073 to recognize backslashes as escape characters. */
2074 match = strmatch (pattern, word, FNMATCH_EXTFLAG) != FNM_NOMATCH;
2081 if (clauses->action && ignore_return)
2082 clauses->action->flags |= CMD_IGNORE_RETURN;
2083 retval = execute_command (clauses->action);
2093 discard_unwind_frame ("case");
2100 /* The WHILE command. Syntax: WHILE test DO action; DONE.
2101 Repeatedly execute action while executing test produces
2102 EXECUTION_SUCCESS. */
2104 execute_while_command (while_command)
2105 WHILE_COM *while_command;
2107 return (execute_while_or_until (while_command, CMD_WHILE));
2110 /* UNTIL is just like WHILE except that the test result is negated. */
2112 execute_until_command (while_command)
2113 WHILE_COM *while_command;
2115 return (execute_while_or_until (while_command, CMD_UNTIL));
2118 /* The body for both while and until. The only difference between the
2119 two is that the test value is treated differently. TYPE is
2120 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2121 be EXECUTION_SUCCESS if no commands in the body are executed, and
2122 the status of the last command executed in the body otherwise. */
2124 execute_while_or_until (while_command, type)
2125 WHILE_COM *while_command;
2128 int return_value, body_status;
2130 body_status = EXECUTION_SUCCESS;
2133 while_command->test->flags |= CMD_IGNORE_RETURN;
2134 if (while_command->flags & CMD_IGNORE_RETURN)
2135 while_command->action->flags |= CMD_IGNORE_RETURN;
2139 return_value = execute_command (while_command->test);
2142 /* Need to handle `break' in the test when we would break out of the
2143 loop. The job control code will set `breaking' to loop_level
2144 when a job in a loop is stopped with SIGTSTP. If the stopped job
2145 is in the loop test, `breaking' will not be reset unless we do
2146 this, and the shell will cease to execute commands. */
2147 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2153 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2161 body_status = execute_command (while_command->action);
2179 return (body_status);
2182 /* IF test THEN command [ELSE command].
2183 IF also allows ELIF in the place of ELSE IF, but
2184 the parser makes *that* stupidity transparent. */
2186 execute_if_command (if_command)
2191 if_command->test->flags |= CMD_IGNORE_RETURN;
2192 return_value = execute_command (if_command->test);
2194 if (return_value == EXECUTION_SUCCESS)
2198 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2199 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2201 return (execute_command (if_command->true_case));
2207 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2208 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2210 return (execute_command (if_command->false_case));
2214 #if defined (DPAREN_ARITHMETIC)
2216 execute_arith_command (arith_command)
2217 ARITH_COM *arith_command;
2225 this_command_name = "(("; /* )) */
2226 /* If we're in a function, update the line number information. */
2227 if (variable_context)
2228 line_number = arith_command->line - function_line_number;
2230 new = expand_words (arith_command->exp);
2232 /* If we're tracing, make a new word list with `((' at the front and `))'
2233 at the back and print it. */
2234 if (echo_command_at_execute)
2235 xtrace_print_arith_cmd (new);
2237 expresult = evalexp (new->word->word, &expok);
2238 dispose_words (new);
2241 return (EXECUTION_FAILURE);
2243 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2245 #endif /* DPAREN_ARITHMETIC */
2247 #if defined (COND_COMMAND)
2249 static char *nullstr = "";
2252 execute_cond_node (cond)
2255 int result, invert, patmatch;
2258 invert = (cond->flags & CMD_INVERT_RETURN);
2260 if (cond->type == COND_EXPR)
2261 result = execute_cond_node (cond->left);
2262 else if (cond->type == COND_OR)
2264 result = execute_cond_node (cond->left);
2265 if (result != EXECUTION_SUCCESS)
2266 result = execute_cond_node (cond->right);
2268 else if (cond->type == COND_AND)
2270 result = execute_cond_node (cond->left);
2271 if (result == EXECUTION_SUCCESS)
2272 result = execute_cond_node (cond->right);
2274 else if (cond->type == COND_UNARY)
2276 arg1 = cond_expand_word (cond->left->op, 0);
2279 if (echo_command_at_execute)
2280 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2281 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2282 if (arg1 != nullstr)
2285 else if (cond->type == COND_BINARY)
2287 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2288 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2289 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
2291 arg1 = cond_expand_word (cond->left->op, 0);
2294 arg2 = cond_expand_word (cond->right->op, patmatch);
2298 if (echo_command_at_execute)
2299 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2301 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2303 : EXECUTION_FAILURE;
2304 if (arg1 != nullstr)
2306 if (arg2 != nullstr)
2311 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
2312 jump_to_top_level (DISCARD);
2313 result = EXECUTION_FAILURE;
2317 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2323 execute_cond_command (cond_command)
2324 COND_COM *cond_command;
2328 result = EXECUTION_SUCCESS;
2330 this_command_name = "[[";
2331 /* If we're in a function, update the line number information. */
2332 if (variable_context)
2333 line_number = cond_command->line - function_line_number;
2336 debug_print_cond_command (cond_command);
2338 last_command_exit_value = result = execute_cond_node (cond_command);
2341 #endif /* COND_COMMAND */
2351 var = bind_variable ("_", arg);
2352 VUNSETATTR (var, att_exported);
2355 /* Execute a null command. Fork a subshell if the command uses pipes or is
2356 to be run asynchronously. This handles all the side effects that are
2357 supposed to take place. */
2359 execute_null_command (redirects, pipe_in, pipe_out, async, old_last_command_subst_pid)
2360 REDIRECT *redirects;
2361 int pipe_in, pipe_out, async;
2362 pid_t old_last_command_subst_pid;
2364 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2366 /* We have a null command, but we really want a subshell to take
2367 care of it. Just fork, do piping and redirections, and exit. */
2368 if (make_child ((char *)NULL, async) == 0)
2370 /* Cancel traps, in trap.c. */
2371 restore_original_signals (); /* XXX */
2373 do_piping (pipe_in, pipe_out);
2375 subshell_environment = SUBSHELL_ASYNC;
2377 if (do_redirections (redirects, 1, 0, 0) == 0)
2378 exit (EXECUTION_SUCCESS);
2380 exit (EXECUTION_FAILURE);
2384 close_pipes (pipe_in, pipe_out);
2385 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2386 unlink_fifo_list ();
2388 return (EXECUTION_SUCCESS);
2393 /* Even if there aren't any command names, pretend to do the
2394 redirections that are specified. The user expects the side
2395 effects to take place. If the redirections fail, then return
2396 failure. Otherwise, if a command substitution took place while
2397 expanding the command or a redirection, return the value of that
2398 substitution. Otherwise, return EXECUTION_SUCCESS. */
2400 if (do_redirections (redirects, 0, 0, 0) != 0)
2401 return (EXECUTION_FAILURE);
2402 else if (old_last_command_subst_pid != last_command_subst_pid)
2403 return (last_command_exit_value);
2405 return (EXECUTION_SUCCESS);
2409 /* This is a hack to suppress word splitting for assignment statements
2410 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2412 fix_assignment_words (words)
2421 b = builtin_address_internal (words->word->word, 0);
2422 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2425 for (w = words; w; w = w->next)
2426 if (w->word->flags & W_ASSIGNMENT)
2427 w->word->flags |= (W_NOSPLIT|W_NOGLOB);
2430 /* The meaty part of all the executions. We have to start hacking the
2431 real execution of commands here. Fork a process, set things up,
2432 execute the command. */
2434 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2435 SIMPLE_COM *simple_command;
2436 int pipe_in, pipe_out, async;
2437 struct fd_bitmap *fds_to_close;
2439 WORD_LIST *words, *lastword;
2440 char *command_line, *lastarg, *temp;
2441 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
2442 pid_t old_last_command_subst_pid, old_last_async_pid;
2443 sh_builtin_func_t *builtin;
2446 result = EXECUTION_SUCCESS;
2447 special_builtin_failed = builtin_is_special = 0;
2448 command_line = (char *)0;
2450 /* If we're in a function, update the line number information. */
2451 if (variable_context)
2452 line_number = simple_command->line - function_line_number;
2454 /* Remember what this command line looks like at invocation. */
2455 command_string_index = 0;
2456 print_simple_command (simple_command);
2459 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2461 old_last_command_subst_pid = last_command_subst_pid;
2462 old_last_async_pid = last_asynchronous_pid;
2464 already_forked = dofork = 0;
2466 /* If we're in a pipeline or run in the background, set DOFORK so we
2467 make the child early, before word expansion. This keeps assignment
2468 statements from affecting the parent shell's environment when they
2470 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2472 /* Something like `%2 &' should restart job 2 in the background, not cause
2473 the shell to fork here. */
2474 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2475 simple_command->words && simple_command->words->word &&
2476 simple_command->words->word->word &&
2477 (simple_command->words->word->word[0] == '%'))
2482 /* XXX memory leak if expand_words() error causes a jump_to_top_level */
2483 command_line = savestring (the_printed_command);
2485 /* Do this now, because execute_disk_command will do it anyway in the
2486 vast majority of cases. */
2487 maybe_make_export_env ();
2489 if (make_child (command_line, async) == 0)
2492 simple_command->flags |= CMD_NO_FORK;
2494 subshell_environment = (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2495 ? (SUBSHELL_PIPE|SUBSHELL_FORK)
2496 : (SUBSHELL_ASYNC|SUBSHELL_FORK);
2498 /* We need to do this before piping to handle some really
2499 pathological cases where one of the pipe file descriptors
2502 close_fd_bitmap (fds_to_close);
2504 do_piping (pipe_in, pipe_out);
2505 pipe_in = pipe_out = NO_PIPE;
2507 last_asynchronous_pid = old_last_async_pid;
2511 close_pipes (pipe_in, pipe_out);
2512 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2513 unlink_fifo_list ();
2515 command_line = (char *)NULL; /* don't free this. */
2516 bind_lastarg ((char *)NULL);
2521 /* If we are re-running this as the result of executing the `command'
2522 builtin, do not expand the command words a second time. */
2523 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2525 current_fds_to_close = fds_to_close;
2526 fix_assignment_words (simple_command->words);
2527 words = expand_words (simple_command->words);
2528 current_fds_to_close = (struct fd_bitmap *)NULL;
2531 words = copy_word_list (simple_command->words);
2533 /* It is possible for WORDS not to have anything left in it.
2534 Perhaps all the words consisted of `$foo', and there was
2535 no variable `$foo'. */
2538 result = execute_null_command (simple_command->redirects,
2540 already_forked ? 0 : async,
2541 old_last_command_subst_pid);
2546 bind_lastarg ((char *)NULL);
2547 set_pipestatus_from_exit (result);
2552 lastarg = (char *)NULL;
2554 begin_unwind_frame ("simple-command");
2556 if (echo_command_at_execute)
2557 xtrace_print_word_list (words);
2559 builtin = (sh_builtin_func_t *)NULL;
2560 func = (SHELL_VAR *)NULL;
2561 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2563 /* Posix.2 says special builtins are found before functions. We
2564 don't set builtin_is_special anywhere other than here, because
2565 this path is followed only when the `command' builtin is *not*
2566 being used, and we don't want to exit the shell if a special
2567 builtin executed with `command builtin' fails. `command' is not
2568 a special builtin. */
2569 if (posixly_correct)
2571 builtin = find_special_builtin (words->word->word);
2573 builtin_is_special = 1;
2576 func = find_function (words->word->word);
2579 add_unwind_protect (dispose_words, words);
2582 /* Bind the last word in this command to "$_" after execution. */
2583 for (lastword = words; lastword->next; lastword = lastword->next)
2585 lastarg = lastword->word->word;
2587 #if defined (JOB_CONTROL)
2588 /* Is this command a job control related thing? */
2589 if (words->word->word[0] == '%' && already_forked == 0)
2591 this_command_name = async ? "bg" : "fg";
2592 last_shell_builtin = this_shell_builtin;
2593 this_shell_builtin = builtin_address (this_command_name);
2594 result = (*this_shell_builtin) (words);
2598 /* One other possiblilty. The user may want to resume an existing job.
2599 If they do, find out whether this word is a candidate for a running
2601 if (job_control && already_forked == 0 && async == 0 &&
2602 !first_word_quoted &&
2604 words->word->word[0] &&
2605 !simple_command->redirects &&
2606 pipe_in == NO_PIPE &&
2607 pipe_out == NO_PIPE &&
2608 (temp = get_string_value ("auto_resume")))
2612 int wl, cl, exact_p, substring_p, match, started_status;
2613 register PROCESS *p;
2615 word = words->word->word;
2616 exact_p = STREQ (temp, "exact");
2617 substring_p = STREQ (temp, "substring");
2619 for (i = job_slots - 1; i > -1; i--)
2621 if (jobs[i] == 0 || (JOBSTATE (i) != JSTOPPED))
2629 cl = strlen (p->command);
2630 match = STREQN (p->command, word, cl);
2632 else if (substring_p)
2633 match = strindex (p->command, word) != (char *)0;
2635 match = STREQN (p->command, word, wl);
2643 run_unwind_frame ("simple-command");
2644 this_command_name = "fg";
2645 last_shell_builtin = this_shell_builtin;
2646 this_shell_builtin = builtin_address ("fg");
2648 started_status = start_job (i, 1);
2649 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2651 while (p != jobs[i]->pipe);
2654 #endif /* JOB_CONTROL */
2656 /* Remember the name of this command globally. */
2657 this_command_name = words->word->word;
2661 /* This command could be a shell builtin or a user-defined function.
2662 We have already found special builtins by this time, so we do not
2663 set builtin_is_special. If this is a function or builtin, and we
2664 have pipes, then fork a subshell in here. Otherwise, just execute
2665 the command directly. */
2666 if (func == 0 && builtin == 0)
2667 builtin = find_shell_builtin (this_command_name);
2669 last_shell_builtin = this_shell_builtin;
2670 this_shell_builtin = builtin;
2672 if (builtin || func)
2676 /* reset_terminating_signals (); */ /* XXX */
2677 /* Cancel traps, in trap.c. */
2678 restore_original_signals ();
2682 if ((simple_command->flags & CMD_STDIN_REDIR) &&
2683 pipe_in == NO_PIPE &&
2684 (stdin_redirects (simple_command->redirects) == 0))
2685 async_redirect_stdin ();
2686 setup_async_signals ();
2689 execute_subshell_builtin_or_function
2690 (words, simple_command->redirects, builtin, func,
2691 pipe_in, pipe_out, async, fds_to_close,
2692 simple_command->flags);
2696 result = execute_builtin_or_function
2697 (words, builtin, func, simple_command->redirects, fds_to_close,
2698 simple_command->flags);
2701 if (result > EX_SHERRBASE)
2703 result = builtin_status (result);
2704 if (builtin_is_special)
2705 special_builtin_failed = 1;
2707 /* In POSIX mode, if there are assignment statements preceding
2708 a special builtin, they persist after the builtin
2710 if (posixly_correct && builtin_is_special && temporary_env)
2711 merge_temporary_env ();
2715 if (result == EX_USAGE)
2716 result = EX_BADUSAGE;
2717 else if (result > EX_SHERRBASE)
2718 result = EXECUTION_FAILURE;
2721 set_pipestatus_from_exit (result);
2727 if (command_line == 0)
2728 command_line = savestring (the_printed_command);
2730 execute_disk_command (words, simple_command->redirects, command_line,
2731 pipe_in, pipe_out, async, fds_to_close,
2732 simple_command->flags);
2735 bind_lastarg (lastarg);
2736 FREE (command_line);
2737 run_unwind_frame ("simple-command");
2741 /* Translate the special builtin exit statuses. We don't really need a
2742 function for this; it's a placeholder for future work. */
2744 builtin_status (result)
2758 r = EXECUTION_FAILURE;
2761 r = EXECUTION_SUCCESS;
2768 execute_builtin (builtin, words, flags, subshell)
2769 sh_builtin_func_t *builtin;
2771 int flags, subshell;
2773 int old_e_flag, result, eval_unwind;
2775 old_e_flag = exit_immediately_on_error;
2776 /* The eval builtin calls parse_and_execute, which does not know about
2777 the setting of flags, and always calls the execution functions with
2778 flags that will exit the shell on an error if -e is set. If the
2779 eval builtin is being called, and we're supposed to ignore the exit
2780 value of the command, we turn the -e flag off ourselves, then
2781 restore it when the command completes. */
2782 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
2784 begin_unwind_frame ("eval_builtin");
2785 unwind_protect_int (exit_immediately_on_error);
2786 exit_immediately_on_error = 0;
2792 /* The temporary environment for a builtin is supposed to apply to
2793 all commands executed by that builtin. Currently, this is a
2794 problem only with the `source' and `eval' builtins. */
2795 if (builtin == source_builtin || builtin == eval_builtin)
2798 begin_unwind_frame ("builtin_env");
2802 builtin_env = copy_array (temporary_env);
2804 add_unwind_protect (dispose_builtin_env, (char *)NULL);
2805 dispose_used_env_vars ();
2807 /* Otherwise we inherit builtin_env from our caller. */
2810 /* `return' does a longjmp() back to a saved environment in execute_function.
2811 If a variable assignment list preceded the command, and the shell is
2812 running in POSIX mode, we need to merge that into the shell_variables
2813 table, since `return' is a POSIX special builtin. */
2814 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
2816 begin_unwind_frame ("return_temp_env");
2817 add_unwind_protect (merge_temporary_env, (char *)NULL);
2820 result = ((*builtin) (words->next));
2822 /* This shouldn't happen, but in case `return' comes back instead of
2823 longjmp'ing, we need to unwind. */
2824 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
2825 discard_unwind_frame ("return_temp_env");
2827 if (subshell == 0 && (builtin == source_builtin || builtin == eval_builtin))
2829 /* In POSIX mode, if any variable assignments precede the `.' or
2830 `eval' builtin, they persist after the builtin completes, since `.'
2831 and `eval' are special builtins. */
2832 if (posixly_correct && builtin_env)
2833 merge_builtin_env ();
2835 run_unwind_frame ("builtin_env");
2840 exit_immediately_on_error += old_e_flag;
2841 discard_unwind_frame ("eval_builtin");
2848 execute_function (var, words, flags, fds_to_close, async, subshell)
2852 struct fd_bitmap *fds_to_close;
2853 int async, subshell;
2855 int return_val, result;
2857 char *debug_trap, *error_trap;
2861 tc = (COMMAND *)copy_command (function_cell (var));
2862 if (tc && (flags & CMD_IGNORE_RETURN))
2863 tc->flags |= CMD_IGNORE_RETURN;
2867 begin_unwind_frame ("function_calling");
2869 add_unwind_protect (pop_context, (char *)NULL);
2870 unwind_protect_int (line_number);
2871 unwind_protect_int (return_catch_flag);
2872 unwind_protect_jmp_buf (return_catch);
2873 add_unwind_protect (dispose_command, (char *)tc);
2874 unwind_protect_pointer (this_shell_function);
2875 unwind_protect_int (loop_level);
2878 this_shell_function = var;
2879 make_funcname_visible (1);
2881 debug_trap = TRAP_STRING(DEBUG_TRAP);
2882 error_trap = TRAP_STRING(ERROR_TRAP);
2884 /* The order of the unwind protects for debug_trap and error_trap is
2885 important here! unwind-protect commands are run in reverse order
2886 of registration. If this causes problems, take out the xfree
2887 unwind-protect calls and live with the small memory leak. */
2892 debug_trap = savestring (debug_trap);
2893 add_unwind_protect (xfree, debug_trap);
2894 add_unwind_protect (set_debug_trap, debug_trap);
2896 restore_default_signal (DEBUG_TRAP);
2903 error_trap = savestring (error_trap);
2904 add_unwind_protect (xfree, error_trap);
2905 add_unwind_protect (set_error_trap, error_trap);
2907 restore_default_signal (ERROR_TRAP);
2910 /* The temporary environment for a function is supposed to apply to
2911 all commands executed within the function body. */
2914 function_env = copy_array (temporary_env);
2915 /* In POSIX mode, variable assignments preceding function names are
2916 supposed to persist in the environment after the function returns,
2917 as if a special builtin command had been executed. */
2920 if (posixly_correct)
2921 add_unwind_protect (merge_function_env, (char *)NULL);
2923 add_unwind_protect (dispose_function_env, (char *)NULL);
2925 dispose_used_env_vars ();
2927 /* Otherwise, we inherit function_env from our caller. */
2929 remember_args (words->next, 1);
2931 /* Number of the line on which the function body starts. */
2932 line_number = function_line_number = tc->line;
2936 #if defined (JOB_CONTROL)
2937 stop_pipeline (async, (COMMAND *)NULL);
2939 fc = (tc->type == cm_group) ? tc->value.Group->command : tc;
2941 if (fc && (flags & CMD_IGNORE_RETURN))
2942 fc->flags |= CMD_IGNORE_RETURN;
2949 return_catch_flag++;
2950 return_val = setjmp (return_catch);
2953 result = return_catch_value;
2955 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
2958 run_unwind_frame ("function_calling");
2960 if (variable_context == 0 || this_shell_function == 0)
2961 make_funcname_visible (0);
2966 /* A convenience routine for use by other parts of the shell to execute
2967 a particular shell function. */
2969 execute_shell_function (var, words)
2974 struct fd_bitmap *bitmap;
2976 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
2977 begin_unwind_frame ("execute-shell-function");
2978 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
2980 ret = execute_function (var, words, 0, bitmap, 0, 0);
2982 dispose_fd_bitmap (bitmap);
2983 discard_unwind_frame ("execute-shell-function");
2988 /* Execute a shell builtin or function in a subshell environment. This
2989 routine does not return; it only calls exit(). If BUILTIN is non-null,
2990 it points to a function to call to execute a shell builtin; otherwise
2991 VAR points at the body of a function to execute. WORDS is the arguments
2992 to the command, REDIRECTS specifies redirections to perform before the
2993 command is executed. */
2995 execute_subshell_builtin_or_function (words, redirects, builtin, var,
2996 pipe_in, pipe_out, async, fds_to_close,
2999 REDIRECT *redirects;
3000 sh_builtin_func_t *builtin;
3002 int pipe_in, pipe_out, async;
3003 struct fd_bitmap *fds_to_close;
3007 #if defined (JOB_CONTROL)
3010 jobs_hack = (builtin == jobs_builtin) &&
3011 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
3014 /* A subshell is neither a login shell nor interactive. */
3015 login_shell = interactive = 0;
3017 subshell_environment = SUBSHELL_ASYNC;
3019 maybe_make_export_env (); /* XXX - is this needed? */
3021 #if defined (JOB_CONTROL)
3022 /* Eradicate all traces of job control after we fork the subshell, so
3023 all jobs begun by this subshell are in the same process group as
3024 the shell itself. */
3026 /* Allow the output of `jobs' to be piped. */
3028 kill_current_pipeline ();
3030 without_job_control ();
3032 set_sigchld_handler ();
3033 #endif /* JOB_CONTROL */
3035 set_sigint_handler ();
3038 close_fd_bitmap (fds_to_close);
3040 do_piping (pipe_in, pipe_out);
3042 if (do_redirections (redirects, 1, 0, 0) != 0)
3043 exit (EXECUTION_FAILURE);
3047 /* Give builtins a place to jump back to on failure,
3048 so we don't go back up to main(). */
3049 result = setjmp (top_level);
3051 if (result == EXITPROG)
3052 exit (last_command_exit_value);
3054 exit (EXECUTION_FAILURE);
3057 r = execute_builtin (builtin, words, flags, 1);
3064 exit (execute_function (var, words, flags, fds_to_close, async, 1));
3067 /* Execute a builtin or function in the current shell context. If BUILTIN
3068 is non-null, it is the builtin command to execute, otherwise VAR points
3069 to the body of a function. WORDS are the command's arguments, REDIRECTS
3070 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
3071 file descriptors to close.
3073 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
3074 not undone before this function returns. */
3076 execute_builtin_or_function (words, builtin, var, redirects,
3077 fds_to_close, flags)
3079 sh_builtin_func_t *builtin;
3081 REDIRECT *redirects;
3082 struct fd_bitmap *fds_to_close;
3086 REDIRECT *saved_undo_list;
3087 sh_builtin_func_t *saved_this_shell_builtin;
3089 if (do_redirections (redirects, 1, 1, 0) != 0)
3091 cleanup_redirects (redirection_undo_list);
3092 redirection_undo_list = (REDIRECT *)NULL;
3093 dispose_exec_redirects ();
3094 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
3097 saved_this_shell_builtin = this_shell_builtin;
3098 saved_undo_list = redirection_undo_list;
3100 /* Calling the "exec" builtin changes redirections forever. */
3101 if (builtin == exec_builtin)
3103 dispose_redirects (saved_undo_list);
3104 saved_undo_list = exec_redirection_undo_list;
3105 exec_redirection_undo_list = (REDIRECT *)NULL;
3108 dispose_exec_redirects ();
3110 if (saved_undo_list)
3112 begin_unwind_frame ("saved redirects");
3113 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
3116 redirection_undo_list = (REDIRECT *)NULL;
3119 result = execute_builtin (builtin, words, flags, 0);
3121 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3123 /* If we are executing the `command' builtin, but this_shell_builtin is
3124 set to `exec_builtin', we know that we have something like
3125 `command exec [redirection]', since otherwise `exec' would have
3126 overwritten the shell and we wouldn't get here. In this case, we
3127 want to behave as if the `command' builtin had not been specified
3128 and preserve the redirections. */
3129 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
3131 if (saved_undo_list)
3132 dispose_redirects (saved_undo_list);
3133 redirection_undo_list = exec_redirection_undo_list;
3134 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
3135 discard_unwind_frame ("saved_redirects");
3138 if (saved_undo_list)
3140 redirection_undo_list = saved_undo_list;
3141 discard_unwind_frame ("saved redirects");
3144 if (redirection_undo_list)
3146 cleanup_redirects (redirection_undo_list);
3147 redirection_undo_list = (REDIRECT *)NULL;
3154 setup_async_signals ()
3156 #if defined (__BEOS__)
3157 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3160 #if defined (JOB_CONTROL)
3161 if (job_control == 0)
3164 set_signal_handler (SIGINT, SIG_IGN);
3165 set_signal_ignored (SIGINT);
3166 set_signal_handler (SIGQUIT, SIG_IGN);
3167 set_signal_ignored (SIGQUIT);
3171 /* Execute a simple command that is hopefully defined in a disk file
3176 3) look up the command
3179 6) If the execve failed, see if the file has executable mode set.
3180 If so, and it isn't a directory, then execute its contents as
3183 Note that the filename hashing stuff has to take place up here,
3184 in the parent. This is probably why the Bourne style shells
3185 don't handle it, since that would require them to go through
3186 this gnarly hair, for no good reason. */
3188 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
3189 async, fds_to_close, cmdflags)
3191 REDIRECT *redirects;
3193 int pipe_in, pipe_out, async;
3194 struct fd_bitmap *fds_to_close;
3197 char *pathname, *command, **args;
3201 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
3202 pathname = words->word->word;
3204 #if defined (RESTRICTED_SHELL)
3205 if (restricted && strchr (pathname, '/'))
3207 internal_error ("%s: restricted: cannot specify `/' in command names",
3209 last_command_exit_value = EXECUTION_FAILURE;
3212 #endif /* RESTRICTED_SHELL */
3214 command = search_for_command (pathname);
3218 maybe_make_export_env ();
3219 put_command_name_into_env (command);
3222 /* We have to make the child before we check for the non-existence
3223 of COMMAND, since we want the error messages to be redirected. */
3224 /* If we can get away without forking and there are no pipes to deal with,
3225 don't bother to fork, just directly exec the command. */
3226 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3229 pid = make_child (savestring (command_line), async);
3233 int old_interactive;
3236 /* This has been disabled for the time being. */
3237 #if !defined (ARG_MAX) || ARG_MAX >= 10240
3238 if (posixly_correct == 0)
3239 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
3243 /* Cancel traps, in trap.c. */
3244 restore_original_signals ();
3246 /* restore_original_signals may have undone the work done
3247 by make_child to ensure that SIGINT and SIGQUIT are ignored
3248 in asynchronous children. */
3251 if ((cmdflags & CMD_STDIN_REDIR) &&
3252 pipe_in == NO_PIPE &&
3253 (stdin_redirects (redirects) == 0))
3254 async_redirect_stdin ();
3255 setup_async_signals ();
3258 /* This functionality is now provided by close-on-exec of the
3259 file descriptors manipulated by redirection and piping.
3260 Some file descriptors still need to be closed in all children
3261 because of the way bash does pipes; fds_to_close is a
3262 bitmap of all such file descriptors. */
3264 close_fd_bitmap (fds_to_close);
3266 do_piping (pipe_in, pipe_out);
3268 old_interactive = interactive;
3272 subshell_environment = SUBSHELL_FORK;
3274 if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
3276 #if defined (PROCESS_SUBSTITUTION)
3277 /* Try to remove named pipes that may have been created as the
3278 result of redirections. */
3279 unlink_fifo_list ();
3280 #endif /* PROCESS_SUBSTITUTION */
3281 exit (EXECUTION_FAILURE);
3285 interactive = old_interactive;
3289 internal_error ("%s: command not found", pathname);
3290 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3293 /* Execve expects the command name to be in args[0]. So we
3294 leave it there, in the same format that the user used to
3296 args = word_list_to_argv (words, 0, 0, (int *)NULL);
3297 exit (shell_execve (command, args, export_env));
3301 /* Make sure that the pipes are closed in the parent. */
3302 close_pipes (pipe_in, pipe_out);
3303 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3304 unlink_fifo_list ();
3310 /* CPP defines to decide whether a particular index into the #! line
3311 corresponds to a valid interpreter name or argument character, or
3312 whitespace. The MSDOS define is to allow \r to be treated the same
3315 #if !defined (MSDOS)
3316 # define STRINGCHAR(ind) \
3317 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
3318 # define WHITECHAR(ind) \
3319 (ind < sample_len && whitespace (sample[ind]))
3321 # define STRINGCHAR(ind) \
3322 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
3323 # define WHITECHAR(ind) \
3324 (ind < sample_len && whitespace (sample[ind]))
3328 getinterp (sample, sample_len, endp)
3330 int sample_len, *endp;
3336 /* Find the name of the interpreter to exec. */
3337 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
3340 for (start = i; STRINGCHAR(i); i++)
3343 execname = substring (sample, start, i);
3350 #if !defined (HAVE_HASH_BANG_EXEC)
3351 /* If the operating system on which we're running does not handle
3352 the #! executable format, then help out. SAMPLE is the text read
3353 from the file, SAMPLE_LEN characters. COMMAND is the name of
3354 the script; it and ARGS, the arguments given by the user, will
3355 become arguments to the specified interpreter. ENV is the environment
3356 to pass to the interpreter.
3358 The word immediately following the #! is the interpreter to execute.
3359 A single argument to the interpreter is allowed. */
3362 execute_shell_script (sample, sample_len, command, args, env)
3368 char *execname, *firstarg;
3369 int i, start, size_increment, larry;
3371 /* Find the name of the interpreter to exec. */
3372 execname = getinterp (sample, sample_len, &i);
3375 /* Now the argument, if any. */
3376 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
3379 /* If there is more text on the line, then it is an argument for the
3384 for (start = i; STRINGCHAR(i); i++)
3386 firstarg = substring ((char *)sample, start, i);
3390 larry = array_len (args) + size_increment;
3392 args = (char **)xrealloc ((char *)args, (1 + larry) * sizeof (char *));
3394 for (i = larry - 1; i; i--)
3395 args[i] = args[i - size_increment];
3406 args[larry] = (char *)NULL;
3408 return (shell_execve (execname, args, env));
3413 #endif /* !HAVE_HASH_BANG_EXEC */
3416 initialize_subshell ()
3419 /* Forget about any aliases that we knew of. We are in a subshell. */
3420 delete_all_aliases ();
3423 #if defined (HISTORY)
3424 /* Forget about the history lines we have read. This is a non-interactive
3426 history_lines_this_session = 0;
3429 #if defined (JOB_CONTROL)
3430 /* Forget about the way job control was working. We are in a subshell. */
3431 without_job_control ();
3432 set_sigchld_handler ();
3433 #endif /* JOB_CONTROL */
3435 /* Reset the values of the shell flags and options. */
3436 reset_shell_flags ();
3437 reset_shell_options ();
3438 reset_shopt_options ();
3440 /* Zero out builtin_env, since this could be a shell script run from a
3441 sourced file with a temporary environment supplied to the `source/.'
3442 builtin. Such variables are not supposed to be exported (empirical
3443 testing with sh and ksh). */
3446 clear_unwind_protect_list (0);
3448 /* We're no longer inside a shell function. */
3449 variable_context = return_catch_flag = 0;
3451 /* If we're not interactive, close the file descriptor from which we're
3452 reading the current shell script. */
3453 if (interactive_shell == 0)
3454 unset_bash_input (1);
3457 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3458 # define SETOSTYPE(x) __setostype(x)
3460 # define SETOSTYPE(x)
3463 #define READ_SAMPLE_BUF(file, buf, len) \
3466 fd = open(file, O_RDONLY); \
3469 len = read (fd, buf, 80); \
3477 /* Call execve (), handling interpreting shell scripts, and handling
3480 shell_execve (command, args, env)
3489 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3490 execve (command, args, env);
3491 i = errno; /* error from execve() */
3494 /* If we get to this point, then start checking out the file.
3495 Maybe it is something we can hack ourselves. */
3498 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3499 internal_error ("%s: is a directory", command);
3502 #if defined (HAVE_HASH_BANG_EXEC)
3503 READ_SAMPLE_BUF (command, sample, sample_len);
3504 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3508 interp = getinterp (sample, sample_len, (int *)NULL);
3510 sys_error ("%s: %s: bad interpreter", command, interp ? interp : "");
3516 file_error (command);
3518 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3521 /* This file is executable.
3522 If it begins with #!, then help out people with losing operating
3523 systems. Otherwise, check to see if it is a binary file by seeing
3524 if the contents of the first line (or up to 80 characters) are in the
3525 ASCII set. If it's a text file, execute the contents as shell commands,
3526 otherwise return 126 (EX_BINARY_FILE). */
3527 READ_SAMPLE_BUF (command, sample, sample_len);
3529 if (sample_len == 0)
3530 return (EXECUTION_SUCCESS);
3532 /* Is this supposed to be an executable script?
3533 If so, the format of the line is "#! interpreter [argument]".
3534 A single argument is allowed. The BSD kernel restricts
3535 the length of the entire line to 32 characters (32 bytes
3536 being the size of the BSD exec header), but we allow 80
3540 #if !defined (HAVE_HASH_BANG_EXEC)
3541 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3542 return (execute_shell_script (sample, sample_len, command, args, env));
3545 if (check_binary_file (sample, sample_len))
3547 internal_error ("%s: cannot execute binary file", command);
3548 return (EX_BINARY_FILE);
3552 /* We have committed to attempting to execute the contents of this file
3553 as shell commands. */
3555 initialize_subshell ();
3557 set_sigint_handler ();
3559 /* Insert the name of this shell into the argument list. */
3560 larray = array_len (args) + 1;
3561 args = (char **)xrealloc ((char *)args, (1 + larray) * sizeof (char *));
3563 for (i = larray - 1; i; i--)
3564 args[i] = args[i - 1];
3566 args[0] = shell_name;
3568 args[larray] = (char *)NULL;
3570 if (args[0][0] == '-')
3573 #if defined (RESTRICTED_SHELL)
3575 change_flag ('r', FLAG_OFF);
3580 /* Can't free subshell_argv[0]; that is shell_name. */
3581 for (i = 1; i < subshell_argc; i++)
3582 free (subshell_argv[i]);
3583 free (subshell_argv);
3586 dispose_command (currently_executing_command); /* XXX */
3587 currently_executing_command = (COMMAND *)NULL;
3589 subshell_argc = larray;
3590 subshell_argv = args;
3591 subshell_envp = env;
3593 unbind_args (); /* remove the positional parameters */
3595 longjmp (subshell_top_level, 1);
3600 execute_intern_function (name, function)
3606 if (check_identifier (name, posixly_correct) == 0)
3608 if (posixly_correct && interactive_shell == 0)
3610 last_command_exit_value = EX_USAGE;
3611 jump_to_top_level (EXITPROG);
3613 return (EXECUTION_FAILURE);
3616 var = find_function (name->word);
3617 if (var && (readonly_p (var) || noassign_p (var)))
3619 if (readonly_p (var))
3620 internal_error ("%s: readonly function", var->name);
3621 return (EXECUTION_FAILURE);
3624 bind_function (name->word, function);
3625 return (EXECUTION_SUCCESS);
3628 #if defined (INCLUDE_UNUSED)
3629 #if defined (PROCESS_SUBSTITUTION)
3633 register int i, fd_table_size;
3635 fd_table_size = getdtablesize ();
3636 if (fd_table_size > 256) /* clamp to a reasonable value */
3637 fd_table_size = 256;
3639 for (i = 3; i < fd_table_size; i++)
3642 #endif /* PROCESS_SUBSTITUTION */
3646 close_pipes (in, out)
3655 /* Redirect input and output to be from and to the specified pipes.
3656 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3658 do_piping (pipe_in, pipe_out)
3659 int pipe_in, pipe_out;
3661 if (pipe_in != NO_PIPE)
3663 if (dup2 (pipe_in, 0) < 0)
3664 sys_error ("cannot duplicate fd %d to fd 0", pipe_in);
3668 if (pipe_out != NO_PIPE)
3670 if (pipe_out != REDIRECT_BOTH)
3672 if (dup2 (pipe_out, 1) < 0)
3673 sys_error ("cannot duplicate fd %d to fd 1", pipe_out);
3674 if (pipe_out == 0 || pipe_out > 1)
3679 if (dup2 (1, 2) < 0)
3680 sys_error ("cannot duplicate fd 1 to fd 2");