1 /* bashhist.c -- bash interface to the GNU history library. */
3 /* Copyright (C) 1993-2015 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
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
25 #if defined (HAVE_UNISTD_H)
27 # include <sys/types.h>
32 #include "bashtypes.h"
36 #include "posixstat.h"
41 #if defined (SYSLOG_HISTORY)
49 #include "parser.h" /* for the struct dstack stuff. */
50 #include "pathexp.h" /* for the struct ignorevar stuff */
51 #include "bashhist.h" /* matching prototypes and declarations */
52 #include "builtins/common.h"
54 #include <readline/history.h>
55 #include <glob/glob.h>
56 #include <glob/strmatch.h>
58 #if defined (READLINE)
59 # include "bashline.h"
60 extern int rl_done
, rl_dispatching
; /* should really include readline.h */
63 #ifndef HISTSIZE_DEFAULT
64 # define HISTSIZE_DEFAULT "500"
71 static int histignore_item_func
__P((struct ign
*));
72 static int check_history_control
__P((char *));
73 static void hc_erasedups
__P((char *));
74 static void really_add_history
__P((char *));
76 static struct ignorevar histignore
=
82 (sh_iv_item_func_t
*)histignore_item_func
,
85 #define HIGN_EXPAND 0x01
87 /* Declarations of bash history variables. */
88 /* Non-zero means to remember lines typed to the shell on the history
89 list. This is different than the user-controlled behaviour; this
90 becomes zero when we read lines from a file, for example. */
91 int remember_on_history
= 0;
92 int enable_history_list
= 0; /* value for `set -o history' */
94 /* The number of lines that Bash has added to this history session. The
95 difference between the number of the top element in the history list
96 (offset from history_base) and the number of lines in the history file.
97 Appending this session's history to the history file resets this to 0. */
98 int history_lines_this_session
;
100 /* The number of lines that Bash has read from the history file. */
101 int history_lines_in_file
;
103 #if defined (BANG_HISTORY)
104 /* Non-zero means do no history expansion on this line, regardless
105 of what history_expansion says. */
106 int history_expansion_inhibited
;
107 /* If non-zero, double quotes can quote the history expansion character. */
108 int double_quotes_inhibit_history_expansion
= 0;
111 /* With the old default, every line was saved in the history individually.
112 I.e., if the user enters:
117 Each line will be individually saved in the history.
124 If the variable command_oriented_history is set, multiple lines
125 which form one command will be saved as one history entry.
136 The user can then recall the whole command all at once instead
137 of just being able to recall one line at a time.
139 This is now enabled by default.
141 int command_oriented_history
= 1;
143 /* Set to 1 if the first line of a possibly-multi-line command was saved
144 in the history list. Managed by maybe_add_history(), but global so
145 the history-manipluating builtins can see it. */
146 int current_command_first_line_saved
= 0;
148 /* Set to the number of the most recent line of a possibly-multi-line command
149 that contains a shell comment. Used by bash_add_history() to determine
150 whether to add a newline or a semicolon. */
151 int current_command_line_comment
= 0;
153 /* Non-zero means to store newlines in the history list when using
154 command_oriented_history rather than trying to use semicolons. */
157 /* Non-zero means to append the history to the history file at shell
158 exit, even if the history has been stifled. */
159 int force_append_history
;
161 /* A nit for picking at history saving. Flags have the following values:
163 Value == 0 means save all lines parsed by the shell on the history.
164 Value & HC_IGNSPACE means save all lines that do not start with a space.
165 Value & HC_IGNDUPS means save all lines that do not match the last
167 Value & HC_ERASEDUPS means to remove all other matching lines from the
168 history list before saving the latest line. */
171 /* Set to 1 if the last command was added to the history list successfully
172 as a separate history entry; set to 0 if the line was ignored or added
173 to a previous entry as part of command-oriented-history processing. */
174 int hist_last_line_added
;
176 /* Set to 1 if builtins/history.def:push_history added the last history
178 int hist_last_line_pushed
;
180 #if defined (READLINE)
181 /* If non-zero, and readline is being used, the user is offered the
182 chance to re-edit a failed history expansion. */
183 int history_reediting
;
185 /* If non-zero, and readline is being used, don't directly execute a
186 line with history substitution. Reload it into the editing buffer
187 instead and let the user further edit and confirm with a newline. */
190 #endif /* READLINE */
192 /* Non-zero means to not save function definitions in the history list. */
193 int dont_save_function_defs
;
195 #if defined (BANG_HISTORY)
196 static int bash_history_inhibit_expansion
__P((char *, int));
198 #if defined (READLINE)
199 static void re_edit
__P((char *));
201 static int history_expansion_p
__P((char *));
202 static int shell_comment
__P((char *));
203 static int should_expand
__P((char *));
204 static HIST_ENTRY
*last_history_entry
__P((void));
205 static char *expand_histignore_pattern
__P((char *));
206 static int history_should_ignore
__P((char *));
208 #if defined (BANG_HISTORY)
209 /* Is the history expansion starting at string[i] one that should not
212 bash_history_inhibit_expansion (string
, i
)
219 hx
[0] = history_expansion_char
;
222 /* The shell uses ! as a pattern negation character in globbing [...]
223 expressions, so let those pass without expansion. */
224 if (i
> 0 && (string
[i
- 1] == '[') && member (']', string
+ i
+ 1))
226 /* The shell uses ! as the indirect expansion character, so let those
227 expansions pass as well. */
228 else if (i
> 1 && string
[i
- 1] == '{' && string
[i
- 2] == '$' &&
229 member ('}', string
+ i
+ 1))
231 /* The shell uses $! as a defined parameter expansion. */
232 else if (i
> 1 && string
[i
- 1] == '$' && string
[i
] == '!')
234 #if defined (EXTENDED_GLOB)
235 else if (extended_glob
&& i
> 1 && string
[i
+1] == '(' && member (')', string
+ i
+ 2))
240 /* If we're supposed to be in single-quoted string, skip over the
241 single-quoted part and then look at what's left. */
242 if (history_quoting_state
== '\'')
244 si
= skip_to_delim (string
, 0, "'", SD_NOJMP
|SD_HISTEXP
);
245 if (string
[si
] == 0 || si
>= i
)
250 /* Make sure the history expansion should not be skipped by quoting or
251 command/process substitution. */
252 if ((t
= skip_to_histexp (string
, si
, hx
, SD_NOJMP
|SD_HISTEXP
)) > 0)
254 /* Skip instances of history expansion appearing on the line before
258 t
= skip_to_histexp (string
, t
+1, hx
, SD_NOJMP
|SD_HISTEXP
);
270 bash_initialize_history ()
272 history_quotes_inhibit_expansion
= 1;
273 history_search_delimiter_chars
= ";&()|<>";
274 #if defined (BANG_HISTORY)
275 history_inhibit_expansion_function
= bash_history_inhibit_expansion
;
276 sv_histchars ("histchars");
281 bash_history_reinit (interact
)
284 #if defined (BANG_HISTORY)
285 history_expansion
= (interact
== 0) ? histexp_flag
: HISTEXPAND_DEFAULT
;
286 history_expansion_inhibited
= (interact
== 0) ? 1 - histexp_flag
: 0; /* changed in bash_history_enable() */
287 history_inhibit_expansion_function
= bash_history_inhibit_expansion
;
289 remember_on_history
= enable_history_list
;
293 bash_history_disable ()
295 remember_on_history
= 0;
296 #if defined (BANG_HISTORY)
297 history_expansion_inhibited
= 1;
302 bash_history_enable ()
304 remember_on_history
= enable_history_list
= 1;
305 #if defined (BANG_HISTORY)
306 history_expansion_inhibited
= 0;
307 history_inhibit_expansion_function
= bash_history_inhibit_expansion
;
309 sv_history_control ("HISTCONTROL");
310 sv_histignore ("HISTIGNORE");
313 /* Load the history list from the history file. */
319 /* Truncate history file for interactive shells which desire it.
320 Note that the history file is automatically truncated to the
321 size of HISTSIZE if the user does not explicitly set the size
323 set_if_not ("HISTSIZE", HISTSIZE_DEFAULT
);
324 sv_histsize ("HISTSIZE");
326 set_if_not ("HISTFILESIZE", get_string_value ("HISTSIZE"));
327 sv_histsize ("HISTFILESIZE");
329 /* Read the history in HISTFILE into the history list. */
330 hf
= get_string_value ("HISTFILE");
332 if (hf
&& *hf
&& file_exists (hf
))
335 /* We have read all of the lines from the history file, even if we
336 read more lines than $HISTSIZE. Remember the total number of lines
337 we read so we don't count the last N lines as new over and over
339 history_lines_in_file
= history_lines_read_from_file
;
341 /* history_lines_in_file = where_history () + history_base - 1; */
346 bash_clear_history ()
349 history_lines_this_session
= 0;
350 /* XXX - reset history_lines_read_from_file? */
353 /* Delete and free the history list entry at offset I. */
355 bash_delete_histent (i
)
360 discard
= remove_history (i
);
362 free_history_entry (discard
);
363 history_lines_this_session
--;
369 bash_delete_history_range (first
, last
)
373 HIST_ENTRY
**discard_list
;
375 discard_list
= remove_history_range (first
, last
);
376 for (i
= 0; discard_list
&& discard_list
[i
]; i
++)
377 free_history_entry (discard_list
[i
]);
378 history_lines_this_session
-= i
;
384 bash_delete_last_history ()
387 HIST_ENTRY
**hlist
, *histent
;
390 hlist
= history_list ();
394 for (i
= 0; hlist
[i
]; i
++)
398 /* History_get () takes a parameter that must be offset by history_base. */
399 histent
= history_get (history_base
+ i
); /* Don't free this */
403 r
= bash_delete_histent (i
);
405 if (where_history () > history_length
)
406 history_set_pos (history_length
);
411 #ifdef INCLUDE_UNUSED
412 /* Write the existing history out to the history file. */
419 hf
= get_string_value ("HISTFILE");
420 if (hf
&& *hf
&& file_exists (hf
))
422 /* Append only the lines that occurred this session to
426 if (history_lines_this_session
<= where_history () || force_append_history
)
427 r
= append_history (history_lines_this_session
, hf
);
429 r
= write_history (hf
);
430 sv_histsize ("HISTFILESIZE");
436 maybe_append_history (filename
)
442 result
= EXECUTION_SUCCESS
;
443 if (history_lines_this_session
> 0 && (history_lines_this_session
<= where_history ()))
445 /* If the filename was supplied, then create it if necessary. */
446 if (stat (filename
, &buf
) == -1 && errno
== ENOENT
)
448 fd
= open (filename
, O_WRONLY
|O_CREAT
, 0600);
451 builtin_error (_("%s: cannot create: %s"), filename
, strerror (errno
));
452 return (EXECUTION_FAILURE
);
456 result
= append_history (history_lines_this_session
, filename
);
457 /* Pretend we already read these lines from the file because we just
459 history_lines_in_file
+= history_lines_this_session
;
460 history_lines_this_session
= 0;
463 history_lines_this_session
= 0; /* reset if > where_history() */
468 /* If this is an interactive shell, then append the lines executed
469 this session to the history file. */
471 maybe_save_shell_history ()
477 if (history_lines_this_session
> 0)
479 hf
= get_string_value ("HISTFILE");
483 /* If the file doesn't exist, then create it. */
484 if (file_exists (hf
) == 0)
487 file
= open (hf
, O_CREAT
| O_TRUNC
| O_WRONLY
, 0600);
492 /* Now actually append the lines if the history hasn't been
493 stifled. If the history has been stifled, rewrite the
496 if (history_lines_this_session
<= where_history () || force_append_history
)
498 result
= append_history (history_lines_this_session
, hf
);
499 history_lines_in_file
+= history_lines_this_session
;
503 result
= write_history (hf
);
504 history_lines_in_file
= history_lines_written_to_file
;
505 /* history_lines_in_file = where_history () + history_base - 1; */
507 history_lines_this_session
= 0;
509 sv_histsize ("HISTFILESIZE");
515 #if defined (READLINE)
516 /* Tell readline () that we have some text for it to edit. */
521 if (bash_input
.type
== st_stdin
)
524 #endif /* READLINE */
526 /* Return 1 if this line needs history expansion. */
528 history_expansion_p (line
)
533 for (s
= line
; *s
; s
++)
534 if (*s
== history_expansion_char
|| *s
== history_subst_char
)
539 /* Do pre-processing on LINE. If PRINT_CHANGES is non-zero, then
540 print the results of expanding the line if there were any changes.
541 If there is an error, return NULL, otherwise the expanded line is
542 returned. If ADDIT is non-zero the line is added to the history
543 list after history expansion. ADDIT is just a suggestion;
544 REMEMBER_ON_HISTORY can veto, and does.
545 Right now this does history expansion. */
547 pre_process_line (line
, print_changes
, addit
)
549 int print_changes
, addit
;
558 # if defined (BANG_HISTORY)
559 /* History expand the line. If this results in no errors, then
560 add that line to the history if ADDIT is non-zero. */
561 if (!history_expansion_inhibited
&& history_expansion
&& history_expansion_p (line
))
565 /* If we are expanding the second or later line of a multi-line
566 command, decrease history_length so references to history expansions
567 in these lines refer to the previous history entry and not the
569 old_len
= history_length
;
570 if (history_length
> 0 && command_oriented_history
&& current_command_first_line_saved
&& current_command_line_count
> 1)
572 expanded
= history_expand (line
, &history_value
);
573 if (history_length
>= 0 && command_oriented_history
&& current_command_first_line_saved
&& current_command_line_count
> 1)
574 history_length
= old_len
;
581 internal_error ("%s", history_value
);
582 #if defined (READLINE)
583 else if (hist_verify
== 0 || expanded
== 2)
587 fprintf (stderr
, "%s\n", history_value
);
590 /* If there was an error, return NULL. */
591 if (expanded
< 0 || expanded
== 2) /* 2 == print only */
593 # if defined (READLINE)
594 if (expanded
== 2 && rl_dispatching
== 0 && *history_value
)
596 if (expanded
== 2 && *history_value
)
597 # endif /* !READLINE */
598 maybe_add_history (history_value
);
600 free (history_value
);
602 # if defined (READLINE)
603 /* New hack. We can allow the user to edit the
604 failed history expansion. */
605 if (history_reediting
&& expanded
< 0 && rl_done
)
607 # endif /* READLINE */
608 return ((char *)NULL
);
611 # if defined (READLINE)
612 if (hist_verify
&& expanded
== 1)
614 re_edit (history_value
);
615 free (history_value
);
616 return ((char *)NULL
);
621 /* Let other expansions know that return_value can be free'ed,
622 and that a line has been added to the history list. Note
623 that we only add lines that have something in them. */
625 return_value
= history_value
;
627 # endif /* BANG_HISTORY */
629 if (addit
&& remember_on_history
&& *return_value
)
630 maybe_add_history (return_value
);
634 return_value
= savestring (line
);
637 return (return_value
);
640 /* Return 1 if the first non-whitespace character in LINE is a `#', indicating
641 that the line is a shell comment. Return 2 if there is a comment after the
642 first non-whitespace character. Return 0 if the line does not contain a
653 for (p
= line
; p
&& *p
&& whitespace (*p
); p
++)
657 n
= skip_to_delim (line
, p
- line
, "#", SD_NOJMP
|SD_GLOB
|SD_EXTGLOB
|SD_COMPLETE
);
658 return (line
[n
] == '#') ? 2 : 0;
661 #ifdef INCLUDE_UNUSED
662 /* Remove shell comments from LINE. A `#' and anything after it is a comment.
663 This isn't really useful yet, since it doesn't handle quoting. */
665 filter_comments (line
)
670 for (p
= line
; p
&& *p
&& *p
!= '#'; p
++)
678 /* Check LINE against what HISTCONTROL says to do. Returns 1 if the line
679 should be saved; 0 if it should be discarded. */
681 check_history_control (line
)
687 if (history_control
== 0)
690 /* ignorespace or ignoreboth */
691 if ((history_control
& HC_IGNSPACE
) && *line
== ' ')
694 /* ignoredups or ignoreboth */
695 if (history_control
& HC_IGNDUPS
)
698 temp
= previous_history ();
700 r
= (temp
== 0 || STREQ (temp
->line
, line
) == 0);
711 /* Remove all entries matching LINE from the history list. Triggered when
712 HISTCONTROL includes `erasedups'. */
721 while (temp
= previous_history ())
723 if (STREQ (temp
->line
, line
))
725 r
= where_history ();
726 temp
= remove_history (r
);
728 free_history_entry (temp
);
734 /* Add LINE to the history list, handling possibly multi-line compound
735 commands. We note whether or not we save the first line of each command
736 (which is usually the entire command and history entry), and don't add
737 the second and subsequent lines of a multi-line compound command if we
738 didn't save the first line. We don't usually save shell comment lines in
739 compound commands in the history, because they could have the effect of
740 commenting out the rest of the command when the entire command is saved as
741 a single history entry (when COMMAND_ORIENTED_HISTORY is enabled). If
742 LITERAL_HISTORY is set, we're saving lines in the history with embedded
743 newlines, so it's OK to save comment lines. If we're collecting the body
744 of a here-document, we should act as if literal_history is enabled, because
745 we want to save the entire contents of the here-document as it was
746 entered. We also make sure to save multiple-line quoted strings or other
749 maybe_add_history (line
)
754 hist_last_line_added
= 0;
755 is_comment
= shell_comment (line
);
757 /* Don't use the value of history_control to affect the second
758 and subsequent lines of a multi-line command (old code did
759 this only when command_oriented_history is enabled). */
760 if (current_command_line_count
> 1)
762 if (current_command_first_line_saved
&&
763 ((parser_state
& PST_HEREDOC
) || literal_history
|| dstack
.delimiter_depth
!= 0 || is_comment
!= 1))
764 bash_add_history (line
);
765 current_command_line_comment
= is_comment
? current_command_line_count
: -2;
769 /* This is the first line of a (possible multi-line) command. Note whether
770 or not we should save the first line and remember it. */
771 current_command_line_comment
= is_comment
? current_command_line_count
: -2;
772 current_command_first_line_saved
= check_add_history (line
, 0);
775 /* Just check LINE against HISTCONTROL and HISTIGNORE and add it to the
776 history if it's OK. Used by `history -s' as well as maybe_add_history().
777 Returns 1 if the line was saved in the history, 0 otherwise. */
779 check_add_history (line
, force
)
783 if (check_history_control (line
) && history_should_ignore (line
) == 0)
785 /* We're committed to saving the line. If the user has requested it,
786 remove other matching lines from the history. */
787 if (history_control
& HC_ERASEDUPS
)
792 really_add_history (line
);
796 bash_add_history (line
);
802 #if defined (SYSLOG_HISTORY)
803 #define SYSLOG_MAXLEN 600
806 #define OPENLOG_OPTS 0
809 #if defined (SYSLOG_SHOPT)
810 int syslog_history
= SYSLOG_SHOPT
;
812 int syslog_history
= 1;
816 bash_syslog_history (line
)
819 char trunc
[SYSLOG_MAXLEN
];
820 static int first
= 1;
824 openlog (shell_name
, OPENLOG_OPTS
, SYSLOG_FACILITY
);
828 if (strlen(line
) < SYSLOG_MAXLEN
)
829 syslog (SYSLOG_FACILITY
|SYSLOG_LEVEL
, "HISTORY: PID=%d UID=%d %s", getpid(), current_user
.uid
, line
);
832 strncpy (trunc
, line
, SYSLOG_MAXLEN
);
833 trunc
[SYSLOG_MAXLEN
- 1] = '\0';
834 syslog (SYSLOG_FACILITY
|SYSLOG_LEVEL
, "HISTORY (TRUNCATED): PID=%d UID=%d %s", getpid(), current_user
.uid
, trunc
);
839 /* Add a line to the history list.
840 The variable COMMAND_ORIENTED_HISTORY controls the style of history
841 remembering; when non-zero, and LINE is not the first line of a
842 complete parser construct, append LINE to the last history line instead
843 of adding it as a new line. */
845 bash_add_history (line
)
848 int add_it
, offset
, curlen
;
849 HIST_ENTRY
*current
, *old
;
850 char *chars_to_add
, *new_line
;
853 if (command_oriented_history
&& current_command_line_count
> 1)
855 /* The second and subsequent lines of a here document have the trailing
856 newline preserved. We don't want to add extra newlines here, but we
857 do want to add one after the first line (which is the command that
858 contains the here-doc specifier). parse.y:history_delimiting_chars()
859 does the right thing to take care of this for us. We don't want to
860 add extra newlines if the user chooses to enable literal_history,
861 so we have to duplicate some of what that function does here. */
862 if ((parser_state
& PST_HEREDOC
) && literal_history
&& current_command_line_count
> 2 && line
[strlen (line
) - 1] == '\n')
864 else if (current_command_line_count
== current_command_line_comment
+1)
866 else if (literal_history
)
869 chars_to_add
= history_delimiting_chars (line
);
872 current
= previous_history ();
874 current_command_line_comment
= shell_comment (line
) ? current_command_line_count
: -2;
878 /* If the previous line ended with an escaped newline (escaped
879 with backslash, but otherwise unquoted), then remove the quoted
880 newline, since that is what happens when the line is parsed. */
881 curlen
= strlen (current
->line
);
883 if (dstack
.delimiter_depth
== 0 && current
->line
[curlen
- 1] == '\\' &&
884 current
->line
[curlen
- 2] != '\\')
886 current
->line
[curlen
- 1] = '\0';
891 /* If we're not in some kind of quoted construct, the current history
892 entry ends with a newline, and we're going to add a semicolon,
893 don't. In some cases, it results in a syntax error (e.g., before
894 a close brace), and it should not be needed. */
895 if (dstack
.delimiter_depth
== 0 && current
->line
[curlen
- 1] == '\n' && *chars_to_add
== ';')
898 new_line
= (char *)xmalloc (1
901 + strlen (chars_to_add
));
902 sprintf (new_line
, "%s%s%s", current
->line
, chars_to_add
, line
);
903 offset
= where_history ();
904 old
= replace_history_entry (offset
, new_line
, current
->data
);
908 free_history_entry (old
);
915 really_add_history (line
);
917 #if defined (SYSLOG_HISTORY)
919 bash_syslog_history (line
);
926 really_add_history (line
)
929 hist_last_line_added
= 1;
930 hist_last_line_pushed
= 0;
932 history_lines_this_session
++;
939 return (remember_on_history
? history_base
+ where_history () : 1);
948 for (p
= s
; p
&& *p
; p
++)
959 histignore_item_func (ign
)
962 if (should_expand (ign
->val
))
963 ign
->flags
|= HIGN_EXPAND
;
968 setup_history_ignore (varname
)
971 setup_ignore_patterns (&histignore
);
975 last_history_entry ()
980 he
= previous_history ();
990 he
= last_history_entry ();
992 return ((char *)NULL
);
997 expand_histignore_pattern (pat
)
1003 phe
= last_history_entry ();
1005 if (phe
== (HIST_ENTRY
*)0)
1006 return (savestring (pat
));
1008 ret
= strcreplace (pat
, '&', phe
->line
, 1);
1013 /* Return 1 if we should not put LINE into the history according to the
1014 patterns in HISTIGNORE. */
1016 history_should_ignore (line
)
1019 register int i
, match
;
1022 if (histignore
.num_ignores
== 0)
1025 for (i
= match
= 0; i
< histignore
.num_ignores
; i
++)
1027 if (histignore
.ignores
[i
].flags
& HIGN_EXPAND
)
1028 npat
= expand_histignore_pattern (histignore
.ignores
[i
].val
);
1030 npat
= histignore
.ignores
[i
].val
;
1032 match
= strmatch (npat
, line
, FNMATCH_EXTFLAG
) != FNM_NOMATCH
;
1034 if (histignore
.ignores
[i
].flags
& HIGN_EXPAND
)
1043 #endif /* HISTORY */