This list is closed, nobody may subscribe to it.
| 2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(12) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2001 |
Jan
(13) |
Feb
(2) |
Mar
(1) |
Apr
(1) |
May
|
Jun
(38) |
Jul
(10) |
Aug
(70) |
Sep
(63) |
Oct
(61) |
Nov
(41) |
Dec
(28) |
| 2002 |
Jan
(43) |
Feb
(11) |
Mar
(9) |
Apr
(2) |
May
(97) |
Jun
(94) |
Jul
(13) |
Aug
(49) |
Sep
(41) |
Oct
(24) |
Nov
(55) |
Dec
(126) |
| 2003 |
Jan
(90) |
Feb
(75) |
Mar
(32) |
Apr
(24) |
May
(54) |
Jun
(54) |
Jul
(22) |
Aug
(4) |
Sep
(16) |
Oct
(8) |
Nov
(6) |
Dec
(13) |
| 2004 |
Jan
|
Feb
(17) |
Mar
(60) |
Apr
(21) |
May
(12) |
Jun
|
Jul
(13) |
Aug
|
Sep
(29) |
Oct
|
Nov
|
Dec
(2) |
| 2005 |
Jan
(22) |
Feb
(3) |
Mar
(2) |
Apr
(13) |
May
(82) |
Jun
(18) |
Jul
(30) |
Aug
(17) |
Sep
(3) |
Oct
(19) |
Nov
(4) |
Dec
(8) |
| 2006 |
Jan
(1) |
Feb
(6) |
Mar
(2) |
Apr
(40) |
May
|
Jun
(21) |
Jul
(1) |
Aug
(410) |
Sep
(3) |
Oct
|
Nov
(56) |
Dec
(7) |
| 2007 |
Jan
(19) |
Feb
|
Mar
(4) |
Apr
(8) |
May
(19) |
Jun
(6) |
Jul
(4) |
Aug
(6) |
Sep
|
Oct
(4) |
Nov
(3) |
Dec
(2) |
| 2008 |
Jan
(13) |
Feb
(18) |
Mar
(12) |
Apr
|
May
(2) |
Jun
|
Jul
|
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
| 2009 |
Jan
|
Feb
(6) |
Mar
(8) |
Apr
(2) |
May
(2) |
Jun
|
Jul
|
Aug
(2) |
Sep
(11) |
Oct
(13) |
Nov
(17) |
Dec
(6) |
| 2010 |
Jan
(24) |
Feb
(10) |
Mar
(27) |
Apr
(20) |
May
(108) |
Jun
(8) |
Jul
(23) |
Aug
(38) |
Sep
(49) |
Oct
(17) |
Nov
(12) |
Dec
(14) |
| 2011 |
Jan
(17) |
Feb
(7) |
Mar
(28) |
Apr
(8) |
May
(20) |
Jun
(11) |
Jul
(7) |
Aug
(12) |
Sep
(4) |
Oct
(20) |
Nov
(19) |
Dec
(2) |
| 2012 |
Jan
(2) |
Feb
(6) |
Mar
(5) |
Apr
(24) |
May
(5) |
Jun
(4) |
Jul
(6) |
Aug
(18) |
Sep
(38) |
Oct
(26) |
Nov
(12) |
Dec
(6) |
| 2013 |
Jan
(19) |
Feb
(18) |
Mar
(44) |
Apr
(35) |
May
(18) |
Jun
(21) |
Jul
(10) |
Aug
(19) |
Sep
(44) |
Oct
(25) |
Nov
(1) |
Dec
(2) |
| 2014 |
Jan
(8) |
Feb
|
Mar
|
Apr
(5) |
May
(1) |
Jun
(3) |
Jul
|
Aug
(3) |
Sep
|
Oct
(4) |
Nov
(4) |
Dec
(7) |
| 2015 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
(2) |
Jun
(4) |
Jul
(6) |
Aug
(2) |
Sep
(8) |
Oct
(2) |
Nov
(1) |
Dec
(3) |
| 2016 |
Jan
(7) |
Feb
(9) |
Mar
(5) |
Apr
(5) |
May
(9) |
Jun
(4) |
Jul
(20) |
Aug
(4) |
Sep
(7) |
Oct
(6) |
Nov
(9) |
Dec
(2) |
| 2017 |
Jan
(7) |
Feb
(7) |
Mar
(5) |
Apr
|
May
(1) |
Jun
(4) |
Jul
(12) |
Aug
(4) |
Sep
(1) |
Oct
(4) |
Nov
(11) |
Dec
(14) |
| 2018 |
Jan
(3) |
Feb
(3) |
Mar
|
Apr
|
May
|
Jun
|
Jul
(2) |
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| S | M | T | W | T | F | S |
|---|---|---|---|---|---|---|
|
1
|
2
|
3
(2) |
4
(1) |
5
|
6
|
7
(1) |
|
8
(1) |
9
|
10
|
11
(2) |
12
|
13
(2) |
14
|
|
15
|
16
|
17
|
18
|
19
(2) |
20
|
21
|
|
22
(71) |
23
|
24
|
25
|
26
|
27
|
28
|
|
29
|
30
|
31
|
|
|
|
|
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:35:51
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/builtins In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv13866/builtins Modified Files: cd.def fc.def Log Message: * ChangeLog: New file. * support/config.guess: Add support for MSYS. * support/config.sub: Ditto. * builtin/cd.def (pwd): Add -W switch. * builtin/fc.def (fc_readline): Handle \r. * subst.c (string_list_dollar_at): Handle win32 separators. (read_comsub): Handle \r. (command_substitute): Ditto. * variables.c (make_variable_value): Path conversion for prefix variable. (bind_variable): Handle \r. * parse.y (yy_getc): Ditto. * y.tab.c (yy_getc): Ditto. Index: cd.def =================================================================== RCS file: /cvsroot/mingw/msys/packages/bash/2.05b/builtins/cd.def,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** cd.def 22 May 2005 10:13:05 -0000 1.1 --- cd.def 22 May 2005 10:35:28 -0000 1.2 *************** *** 292,299 **** $BUILTIN pwd $FUNCTION pwd_builtin ! $SHORT_DOC pwd [-PL] Print the current working directory. With the -P option, pwd prints the physical directory, without any symbolic links; the -L option ! makes pwd follow symbolic links. $END --- 292,300 ---- $BUILTIN pwd $FUNCTION pwd_builtin ! $SHORT_DOC pwd [-PLW] Print the current working directory. With the -P option, pwd prints the physical directory, without any symbolic links; the -L option ! makes pwd follow symbolic links; the -W option makes pwd print the absolute ! windows path. $END *************** *** 312,316 **** verbatim_pwd = no_symbolic_links; reset_internal_getopt (); ! while ((opt = internal_getopt (list, "LP")) != -1) { switch (opt) --- 313,317 ---- verbatim_pwd = no_symbolic_links; reset_internal_getopt (); ! while ((opt = internal_getopt (list, "LPW")) != -1) { switch (opt) *************** *** 322,325 **** --- 323,329 ---- verbatim_pwd = 0; break; + case 'W': + verbatim_pwd = 2; + break; default: builtin_usage (); *************** *** 331,336 **** #define tcwd the_current_working_directory ! directory = tcwd ? (verbatim_pwd ? sh_physpath (tcwd, 0) : tcwd) : get_working_directory ("pwd"); #undef tcwd --- 335,350 ---- #define tcwd the_current_working_directory ! switch (verbatim_pwd) ! { ! case 2: ! { ! directory = xmalloc(PATH_MAX); ! cygwin_conv_to_win32_path (tcwd, directory); ! } ! break; ! default: ! directory = tcwd ? (verbatim_pwd ? sh_physpath (tcwd, 0) : tcwd) : get_working_directory ("pwd"); + } #undef tcwd Index: fc.def =================================================================== RCS file: /cvsroot/mingw/msys/packages/bash/2.05b/builtins/fc.def,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** fc.def 22 May 2005 10:13:05 -0000 1.1 --- fc.def 22 May 2005 10:35:29 -0000 1.2 *************** *** 510,513 **** --- 510,516 ---- { register int c; + #ifdef __MSYS__ + register int d; + #endif int line_len = 0, lindex = 0; char *line = (char *)NULL; *************** *** 520,523 **** --- 523,530 ---- if (c == '\n') { + #ifdef __MSYS__ + if (d == '\r') + lindex==; + #endif line[lindex++] = '\n'; line[lindex++] = '\0'; *************** *** 526,529 **** --- 533,539 ---- else line[lindex++] = c; + #ifdef __MSYS__ + d = c; + #endif } |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:35:38
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv13866 Modified Files: parse.y subst.c variables.c y.tab.c Added Files: ChangeLog.MSYS Log Message: * ChangeLog: New file. * support/config.guess: Add support for MSYS. * support/config.sub: Ditto. * builtin/cd.def (pwd): Add -W switch. * builtin/fc.def (fc_readline): Handle \r. * subst.c (string_list_dollar_at): Handle win32 separators. (read_comsub): Handle \r. (command_substitute): Ditto. * variables.c (make_variable_value): Path conversion for prefix variable. (bind_variable): Handle \r. * parse.y (yy_getc): Ditto. * y.tab.c (yy_getc): Ditto. Index: parse.y =================================================================== RCS file: /cvsroot/mingw/msys/packages/bash/2.05b/parse.y,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** parse.y 22 May 2005 10:13:04 -0000 1.1 --- parse.y 22 May 2005 10:35:27 -0000 1.2 *************** *** 1040,1044 **** --- 1040,1050 ---- yy_getc () { + #ifdef __MSYS__ + int c; + while ((c = (*(bash_input.getter)) ()) == '\r'); + return c; + #else return (*(bash_input.getter)) (); + #endif } Index: y.tab.c =================================================================== RCS file: /cvsroot/mingw/msys/packages/bash/2.05b/y.tab.c,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** y.tab.c 22 May 2005 10:13:04 -0000 1.1 --- y.tab.c 22 May 2005 10:35:27 -0000 1.2 *************** *** 2561,2565 **** --- 2561,2571 ---- yy_getc () { + #ifdef __MSYS__ + int c; + while ((c = (*(bash_input.getter)) ()) == '\r'); + return c; + #else return (*(bash_input.getter)) (); + #endif } *************** *** 3337,3340 **** --- 3343,3350 ---- RESIZE_MALLOCED_BUFFER (shell_input_line, i, 2, shell_input_line_size, 256); + #ifdef __MSYS__ + if (c == '\r') + continue; + #endif if (c == EOF) { Index: variables.c =================================================================== RCS file: /cvsroot/mingw/msys/packages/bash/2.05b/variables.c,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** variables.c 22 May 2005 10:13:04 -0000 1.1 --- variables.c 22 May 2005 10:35:27 -0000 1.2 *************** *** 1601,1604 **** --- 1601,1607 ---- { char *retval; + #ifdef __MSYS__ + char *wbuffer = xmalloc(PATH_MAX); + #endif intmax_t lval; int expok; *************** *** 1625,1628 **** --- 1628,1637 ---- retval[0] = '\0'; } + #ifdef __MSYS__ + if (strncmp (var->name, "prefix", 6) == 0) { + cygwin_conv_to_win32_path (retval, wbuffer); + retval = wbuffer; + } + #endif } else *************** *** 1712,1715 **** --- 1721,1737 ---- VAR_CONTEXT *vc; + #ifdef __MSYS__ + /* Remove trailing \r from value */ + { + char *tpos; + if (value) + { + tpos = strchr (value, '\0'); + tpos--; + if (*tpos == '\r') + *tpos = '\0'; + } + } + #endif if (shell_variables == 0) { *************** *** 2753,2757 **** for (i = 0, list_index = 0; var = vars[i]; i++) { ! #if defined (__CYGWIN__) /* We don't use the exportstr stuff on Cygwin at all. */ INVALIDATE_EXPORTSTR (var); --- 2775,2779 ---- for (i = 0, list_index = 0; var = vars[i]; i++) { ! #if defined (__MSYS__) /* We don't use the exportstr stuff on Cygwin at all. */ INVALIDATE_EXPORTSTR (var); --- NEW FILE: ChangeLog.MSYS --- 2005.05.22 Earnie Boyd <ea...@us...> * ChangeLog: New file. * support/config.guess: Add support for MSYS. * support/config.sub: Ditto. * builtin/cd.def (pwd): Add -W switch. * builtin/fc.def (fc_readline): Handle \r. * subst.c (string_list_dollar_at): Handle win32 separators. (read_comsub): Handle \r. (command_substitute): Ditto. * variables.c (make_variable_value): Path conversion for prefix variable. (bind_variable): Handle \r. * parse.y (yy_getc): Ditto. * y.tab.c (yy_getc): Ditto. Index: subst.c =================================================================== RCS file: /cvsroot/mingw/msys/packages/bash/2.05b/subst.c,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** subst.c 22 May 2005 10:13:04 -0000 1.1 --- subst.c 22 May 2005 10:35:27 -0000 1.2 *************** *** 1639,1647 **** /* This performs word splitting and quoted null character removal on STRING. */ ! #if 0 ! #define issep(c) ((separators)[1] ? (member ((c), separators)) : (c) == (separators)[0]) ! #else ! #define issep(c) ((separators)[1] ? isifs(c) : (c) == (separators)[0]) ! #endif WORD_LIST * --- 1639,1646 ---- /* This performs word splitting and quoted null character removal on STRING. */ ! #define issep(c) \ ! (((separators)[0]) ? ((separators)[1] ? isifs(c) \ ! : (c) == (separators)[0]) \ ! : 0) WORD_LIST * *************** *** 3628,3632 **** istring_index = istring_size = bufn = 0; ! #ifdef __CYGWIN__ setmode (fd, O_TEXT); /* we don't want CR/LF, we want Unix-style */ #endif --- 3627,3631 ---- istring_index = istring_size = bufn = 0; ! #ifdef __MSYS__ setmode (fd, O_TEXT); /* we don't want CR/LF, we want Unix-style */ #endif *************** *** 3663,3667 **** #if 0 ! #if defined (__CYGWIN__) if (c == '\n' && istring_index > 1 && istring[istring_index - 2] == '\r') { --- 3662,3666 ---- #if 0 ! #if defined (__MSYS__) if (c == '\n' && istring_index > 1 && istring[istring_index - 2] == '\r') { *************** *** 3708,3711 **** --- 3707,3722 ---- } + #ifdef __MSYS__ + static inline void RemoveCR(); + static void + RemoveCR (string) + char * string; + { + char *pstr; + if (string && (pstr = strchr (string, '\0')) && *(--pstr) == '\r') + *pstr = '\0'; + } + #endif + /* Perform command substitution on STRING. This returns a string, possibly quoted. */ *************** *** 3718,3721 **** --- 3729,3733 ---- char *istring; int result, fildes[2], function_value; + int i, closeit[3]; istring = (char *)NULL; *************** *** 3744,3747 **** --- 3756,3769 ---- maybe_make_export_env (); /* XXX */ + + for (i = 0; i <= 2; i++) + if (fcntl (i, F_GETFD, &result) != -1) + closeit[i] = 0; + else + { + open ("/dev/null", O_RDONLY); + closeit[i] = 1; + } + /* Pipe the output of executing STRING into the current shell. */ if (pipe (fildes) < 0) *************** *** 3751,3754 **** --- 3773,3780 ---- } + for (i = 0; i <= 2; i++) + if (closeit[i]) + close (i); + old_pid = last_made_pid; #if defined (JOB_CONTROL) *************** *** 3760,3764 **** #endif ! pid = make_child ((char *)NULL, 0); if (pid == 0) /* Reset the signal handlers in the child, but don't free the --- 3786,3790 ---- #endif ! pid = make_child ((char *)NULL, subshell_environment & SUBSHELL_ASYNC); if (pid == 0) /* Reset the signal handlers in the child, but don't free the *************** *** 3795,3813 **** } ! /* If standard output is closed in the parent shell ! (such as after `exec >&-'), file descriptor 1 will be ! the lowest available file descriptor, and end up in ! fildes[0]. This can happen for stdin and stderr as well, ! but stdout is more important -- it will cause no output ! to be generated from this command. */ ! if ((fildes[1] != fileno (stdin)) && ! (fildes[1] != fileno (stdout)) && ! (fildes[1] != fileno (stderr))) ! close (fildes[1]); ! ! if ((fildes[0] != fileno (stdin)) && ! (fildes[0] != fileno (stdout)) && ! (fildes[0] != fileno (stderr))) ! close (fildes[0]); /* The currently executing shell is not interactive. */ --- 3821,3826 ---- } ! close (fildes[1]); ! close (fildes[0]); /* The currently executing shell is not interactive. */ *************** *** 3884,3887 **** --- 3897,3903 ---- #endif /* JOB_CONTROL */ + #ifdef __MSYS__ + RemoveCR (istring); + #endif return (istring); } |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:17:00
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/support In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11107 Modified Files: config.guess config.sub Log Message: Add MSYS for target recognition Index: config.guess =================================================================== RCS file: /cvsroot/mingw/msys/packages/bash/2.05b/support/config.guess,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** config.guess 22 May 2005 10:13:25 -0000 1.1 --- config.guess 22 May 2005 10:16:41 -0000 1.2 *************** *** 785,788 **** --- 785,791 ---- echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit 0 ;; + i*:MSYS*:*) + echo ${UNAME_MACHINE}-pc-msys + exit 0 ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin Index: config.sub =================================================================== RCS file: /cvsroot/mingw/msys/packages/bash/2.05b/support/config.sub,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** config.sub 22 May 2005 10:13:25 -0000 1.1 --- config.sub 22 May 2005 10:16:41 -0000 1.2 *************** *** 580,583 **** --- 580,587 ---- os=-go32 ;; + i386-msys) + basic_machine=i386-pc # bash + os=-msys + ;; i386-mingw32) basic_machine=i386-pc # bash *************** *** 1129,1133 **** | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* \ ! | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \ --- 1133,1137 ---- | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* \ ! | -msys* | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \ |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:36
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/tests/misc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/tests/misc Added Files: dev-tcp.tests perf-script perftest read-nchars.tests redir-t2.sh run-r2.sh sigint-1.sh sigint-2.sh sigint-3.sh sigint-4.sh test-minus-e.1 test-minus-e.2 wait-bg.tests Log Message: Pristine source --- NEW FILE: perf-script --- #!/bin/bash typeset -i m2 m1 M n2 n1 N m n typeset -i MM=5 NN=5 case $# in 0) : ;; 1) MM=$1; NN=$1 ;; 2) MM=$1; NN=$2 ;; *) echo 1>&2 "Usage: $0 [m [n]]" ;; esac EMPTYLINE=: # echo echo 'a = { ' # mathematica let "M=1" # for (M=1; M<=MM; M++) while let "M <= MM"; do let "N=1" # for (N=1; N<=NN; N++) while let "N <= NN"; do let "m1 = M - 1" let "m2 = M + 1" let "n1 = N - 1" let "n2 = N + 1" echo -n '{ ' # math let "m=1" # for(m=1; m<=MM; m++) while let "m <= MM"; do let "n=1" # for(n=1; n<=NN; n++) while let "n <= NN"; do let "x = (m-m1)*(m-M)*(m-m2)" let "y = (n-n1)*(n-N)*(n-n2)" if let "(x*x + (n-N)*(n-N)) * ((m-M)*(m-M) + y*y)"; then echo -n "0," else # neighbour echo -n "1," fi let "n=n+1" done echo -n " "; let "m=m+1" # ". " done echo '},' let "N=N+1" $EMPTYLINE done $EMPTYLINE let "M=M+1" done echo '}' echo -n 'o = { ' let "m=1" while let "m <= MM"; do let "n=1" while let "n <= NN"; do echo -n "1," let "n=n+1" done let "m=m+1" done echo " }" echo 'x = LinearSolve[a,o] ' exit 0 --- NEW FILE: redir-t2.sh --- read line1 echo read line 1 \"$line1\" exec 4<&0 exec 0</dev/tty read line2 echo line read from tty = \"$line2\" exec 0<&4 read line3 echo read line 3 \"$line3\" --- NEW FILE: test-minus-e.2 --- touch .file set -e while set +e ; test -r .file ; do echo -n "stop loop? [yes to quit] " read reply if [ "$reply" = yes ] ; then rm .file non-dash-file fi set -e done rm -f .file --- NEW FILE: perftest --- # originally from Mike Haertel foo() { case $1 in a*) ;; *) ;; esac ;} bar() { case $1 in [abc]*) ;; *);; esac ;} baz() { case $1 in xyzzy) ;; *) ;; esac ;} for x in /usr/lib/*/* do foo $x bar $x baz $x done --- NEW FILE: dev-tcp.tests --- exec 9<>/dev/tcp/129.22.8.162/25 read banner <&9 echo "$banner" echo quit >&9 read msg <&9 echo "$msg" exec 9<&- # nifty date command that queries the date/time server cat < /dev/tcp/129.22.8.102/13 exit 0 --- NEW FILE: sigint-3.sh --- sleep 5 & sleep 5 & sleep 5 & echo wait 1 wait echo wait 2 wait exit --- NEW FILE: read-nchars.tests --- # interactive # from tty read -n 3 -p 'enter three chars: ' xyz echo echo $xyz # using readline read -p 'enter 3 chars: ' -e -n 3 abc # readline outputs a newline for us, so we don't need the extra echo echo $abc --- NEW FILE: sigint-1.sh --- echo before trap trap 'echo caught sigint' 2 echo after trap for i in 1 2 3 do echo $i sleep 5 done --- NEW FILE: run-r2.sh --- ../../bash ./redir-t2.sh < /etc/passwd --- NEW FILE: wait-bg.tests --- #! /bin/bash i=0 while [ $i -lt $1 ] do /bin/sh -c "sleep 4; exit 0" & rv=$? pid=$! eval bg_pid_$i=$pid echo $$: Job $i: pid is $pid rv=$rv i=$((i + 1)) done i=0 while [ $i -lt $1 ] do eval wpid=\$bg_pid_$i echo Waiting for job $i '('pid $wpid')' wait $wpid rv=$? echo Return value is $rv i=$((i + 1)) done --- NEW FILE: test-minus-e.1 --- touch .file while set -e ; test -r .file ; do echo -n "stop loop? " read reply case "$reply" in y*) rm .file non-dash-file ;; esac set +e done --- NEW FILE: sigint-2.sh --- echo before loop for i in 1 2 3 do echo $i sleep 5 done --- NEW FILE: sigint-4.sh --- trap 'echo sigint' 2 sleep 5 & sleep 5 & sleep 5 & echo wait 1 wait echo wait 2 wait exit |
Update of /cvsroot/mingw/msys/packages/bash/2.05b/tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/tests Added Files: README arith-for.right arith-for.tests arith.right arith.tests array-at-star array.right array.tests array2.right braces-tests braces.right builtins.right builtins.tests builtins1.sub builtins2.sub cond.right cond.tests cprint.right cprint.tests dollar-at-star dollar.right dstack.right dstack.tests dstack2.right dstack2.tests errors.right errors.tests exec.right exec1.sub exec2.sub exec3.sub exec4.sub exec5.sub exec6.sub execscript exp-tests exp.right extglob.right extglob.tests extglob2.right extglob2.tests func.right func.tests func1.sub func2.sub func3.sub getopts.right getopts.tests getopts1.sub getopts2.sub getopts3.sub getopts4.sub getopts5.sub getopts6.sub getopts7.sub glob-test glob.right glob1.sub heredoc.right heredoc.tests herestr.right herestr.tests histexp.right histexp.tests history.list history.right history.tests ifs.right ifs.tests input-line.sh input-line.sub input.right invert.right invert.tests jobs.right jobs.tests jobs1.sub jobs2.sub jobs3.sub more-exp.right more-exp.tests new-exp.right new-exp.tests new-exp1.sub new-exp2.sub new-exp3.sub nquote.right nquote.tests nquote1.right nquote1.tests nquote2.right nquote2.tests nquote3.right nquote3.tests posix2.right posix2.tests posixpat.right posixpat.tests prec.right precedence printf.right printf.tests quote.right quote.tests read.right read.tests read1.sub read2.sub read3.sub read4.sub redir.right redir.tests redir1.sub redir2.sub redir3.in1 redir3.in2 redir3.sub redir4.in1 redir4.sub redir5.sub rhs-exp.right rhs-exp.tests rsh.right rsh.tests run-all run-arith run-arith-for run-array run-array2 run-braces run-builtins run-cond run-cprint run-dirstack run-dollars run-errors run-execscript run-exp-tests run-extglob run-extglob2 run-func run-getopts run-glob-test run-heredoc run-herestr run-histexpand run-history run-ifs run-input-test run-invert run-jobs run-minimal run-more-exp run-new-exp run-nquote run-nquote1 run-nquote2 run-nquote3 run-posix2 run-posixpat run-precedence run-printf run-quote run-read run-redir run-rhs-exp run-rsh run-set-e run-shopt run-strip run-test run-tilde run-trap run-type run-varenv set-e-test set-e.right shopt.right shopt.tests source1.sub source2.sub source3.sub source4.sub source5.sub strip.right strip.tests test.right test.tests tilde-tests tilde.right trap.right trap.tests trap1.sub trap2.sub trap2a.sub type.right type.tests varenv.right varenv.sh varenv1.sub varenv2.sub version version.mini Log Message: Pristine source --- NEW FILE: run-varenv --- ${THIS_SH} ./varenv.sh | grep -v '^expect' > /tmp/xx diff /tmp/xx varenv.right && rm -f /tmp/xx --- NEW FILE: run-input-test --- ${THIS_SH} < ./input-line.sh > /tmp/xx diff /tmp/xx input.right && rm -f /tmp/xx --- NEW FILE: precedence --- # @(#)precedence_test 1.0 91/07/24 Maarten Litmaath # test of relative precedences for `&&' and `||' operators echo "\`Say' echos its argument. Its return value is of no interest." case `echo -n` in '') Say () { echo -n "$*" ; } ;; *) Say () { echo "$*\c" ; } ;; esac echo "\`Truth' echos its argument and returns a TRUE result." Truth () { Say $1; return 0; } echo "\`False' echos its argument and returns a FALSE result." False () { Say $1; return 1; } echo "" cmd1='$open $test1 && $test2 $close || $test3' cmd2='$test1 || $open $test2 && $test3 $close' grouping_sh= grouping_C='( )' test3='Say 3' for i in 1 2 do eval proto=\$cmd$i for test1 in 'Truth 1' 'False 1' do for test2 in 'Truth 2' 'False 2' do for precedence in sh C do eval set x \$grouping_$precedence shift open=${1-' '} close=${2-' '} eval cmd=\""$proto"\" Say "$cmd output=" output=`eval "$cmd"` Say "$output" read correct || { echo 'Input fubar. Abort.' >&2; exit 1; } test "X$output" = "X$correct" || echo " correct=$correct" echo '' done echo '' done done done << EOF 12 12 123 123 13 13 13 13 13 1 13 1 123 123 12 12 EOF --- NEW FILE: run-builtins --- ${THIS_SH} ./builtins.tests > /tmp/xx 2>&1 diff /tmp/xx builtins.right && rm -f /tmp/xx --- NEW FILE: run-glob-test --- PATH=$PATH:`pwd` export PATH ${THIS_SH} ./glob-test | grep -v '^expect' > /tmp/xx diff /tmp/xx glob.right && rm -f /tmp/xx --- NEW FILE: run-cprint --- ${THIS_SH} ./cprint.tests > /tmp/xx 2>&1 diff /tmp/xx cprint.right && rm -f /tmp/xx --- NEW FILE: getopts5.sub --- #!/local/bin/bash #Time-stamp: <95/06/07 07:40:40 hr...@im...> getop () { local OPTIND local OPTERR=1 echo getop: OPTERR=$OPTERR while getopts ab arg "$@"; do case $arg in a) echo a here ;; b) echo b here ;; :|?|*) echo something else here ;; esac done echo getop: OPTIND=$OPTIND } OPTIND= OPTERR=0 echo OPTERR=$OPTERR while getopts ab arg; do case $arg in a) echo a here ;; b) echo b here ;; :|?|*) echo something else here ;; esac done echo OPTIND=$OPTIND getop "$@" -d -e echo OPTIND=$OPTIND echo OPTERR=$OPTERR --- NEW FILE: set-e.right --- 95 96 97 98 99 0 1 2 3 4 5 6 7 8 9 1 1 ok hi while succeeded until succeeded: 4 if succeeded AND list succeeded OR list succeeded ! succeeded eval succeeded ! eval succeeded -- 1 ! eval succeeded -- 2 --- NEW FILE: source5.sub --- LC_ALL=en_US unset LC_ALL unset LANG export LC_ALL=C export LANG=C set +o posix # attempting to source a non-existant file is not an error... . /tmp/source-notthere echo after bad source 1 set -o posix # ...unless you're in posix mode . /tmp/source-notthere echo after bad source 2 --- NEW FILE: run-new-exp --- echo "warning: two of these tests will fail if your OS does not support" >&2 echo "warning: named pipes or the /dev/fd filesystem. If the tests of the" >&2 echo "warning: process substitution mechanism fail, please do not consider" >&2 echo "warning: this a test failure" >&2 echo "warning: if you have exported variables beginning with the string _Q," >&2 echo "warning: diff output may be generated. If so, please do not consider" >&2 echo "warning: this a test failure" >&2 ${THIS_SH} ./new-exp.tests 2>&1 | grep -v '^expect' > /tmp/xx diff /tmp/xx new-exp.right && rm -f /tmp/xx --- NEW FILE: arith.tests --- set +o posix declare -i iv jv iv=$(( 3 + 5 * 32 )) echo $iv iv=iv+3 echo $iv iv=2 jv=iv let "jv *= 2" echo $jv jv=$(( $jv << 2 )) echo $jv let jv="$jv / 2" echo $jv jv="jv >> 2" echo $jv iv=$((iv+ $jv)) echo $iv echo $((iv -= jv)) echo $iv echo $(( iv == jv )) echo $(( iv != $jv )) echo $(( iv < jv )) echo $(( $iv > $jv )) echo $(( iv <= $jv )) echo $(( $iv >= jv )) echo $jv echo $(( ~$jv )) echo $(( ~1 )) echo $(( ! 0 )) echo $(( jv % 2 )) echo $(( $iv % 4 )) echo $(( iv <<= 16 )) echo $(( iv %= 33 )) echo $(( 33 & 55 )) echo $(( 33 | 17 )) echo $(( iv && $jv )) echo $(( $iv || jv )) echo $(( iv && 0 )) echo $(( iv & 0 )) echo $(( iv && 1 )) echo $(( iv & 1 )) echo $(( $jv || 0 )) echo $(( jv | 0 )) echo $(( jv | 1 )) echo $(( $jv || 1 )) let 'iv *= jv' echo $iv echo $jv let "jv += $iv" echo $jv echo $(( jv /= iv )) echo $(( jv <<= 8 )) echo $(( jv >>= 4 )) echo $(( iv |= 4 )) echo $(( iv &= 4 )) echo $(( iv += (jv + 9))) echo $(( (iv + 4) % 7 )) # unary plus, minus echo $(( +4 - 8 )) echo $(( -4 + 8 )) # conditional expressions echo $(( 4<5 ? 1 : 32)) echo $(( 4>5 ? 1 : 32)) echo $(( 4>(2+3) ? 1 : 32)) echo $(( 4<(2+3) ? 1 : 32)) echo $(( (2+2)<(2+3) ? 1 : 32)) echo $(( (2+2)>(2+3) ? 1 : 32)) # check that the unevaluated part of the ternary operator does not do # evaluation or assignment x=i+=2 y=j+=2 declare -i i=1 j=1 echo $((1 ? 20 : (x+=2))) echo $i,$x echo $((0 ? (y+=2) : 30)) echo $j,$y x=i+=2 y=j+=2 declare -i i=1 j=1 echo $((1 ? 20 : (x+=2))) echo $i,$x echo $((0 ? (y+=2) : 30)) echo $i,$y # check precedence of assignment vs. conditional operator # should be an error declare -i x=2 y=$((1 ? 20 : x+=2)) # check precedence of assignment vs. conditional operator declare -i x=2 echo $((0 ? x+=2 : 20)) # associativity of assignment-operator operator declare -i i=1 j=2 k=3 echo $((i += j += k)) echo $i,$j,$k # octal, hex echo $(( 0x100 | 007 )) echo $(( 0xff )) echo $(( 16#ff )) echo $(( 16#FF/2 )) echo $(( 8#44 )) echo $(( 8 ^ 32 )) # other bases echo $(( 16#a )) echo $(( 32#a )) echo $(( 56#a )) echo $(( 64#a )) echo $(( 16#A )) echo $(( 32#A )) echo $(( 56#A )) echo $(( 64#A )) echo $(( 64#@ )) echo $(( 64#_ )) # weird bases echo $(( 3425#56 )) # missing number after base echo $(( 2# )) # these should generate errors echo $(( 7 = 43 )) echo $(( 2#44 )) echo $(( 44 / 0 )) let 'jv += $iv' echo $(( jv += \$iv )) let 'rv = 7 + (43 * 6' # more errors declare -i i i=0#4 i=2#110#11 ((echo abc; echo def;); echo ghi) if (((4+4) + (4 + 7))); then echo ok fi (()) # make sure the null expression works OK a=(0 2 4 6) echo $(( a[1] + a[2] )) echo $(( (a[1] + a[2]) == a[3] )) (( (a[1] + a[2]) == a[3] )) ; echo $? # test pushing and popping the expression stack unset A A="4 + " echo $(( ( 4 + A ) + 4 )) A="3 + 5" echo $(( ( 4 + A ) + 4 )) # badly-formed conditional expressions echo $(( 4 ? : $A )) echo $(( 1 ? 20 )) echo $(( 4 ? 20 : )) # precedence and short-circuit evaluation B=9 echo $B echo $(( 0 && B=42 )) echo $B echo $(( 1 || B=88 )) echo $B echo $(( 0 && (B=42) )) echo $B echo $(( (${$} - $$) && (B=42) )) echo $B echo $(( 1 || (B=88) )) echo $B # until command with (( )) command x=7 echo $x until (( x == 4 )) do echo $x x=4 done echo $x # exponentiation echo $(( 2**15 - 1)) echo $(( 2**(16-1))) echo $(( 2**16*2 )) echo $(( 2**31-1)) echo $(( 2**0 )) # {pre,post}-{inc,dec}rement and associated errors x=4 echo $x echo $(( x++ )) echo $x echo $(( x-- )) echo $x echo $(( --x )) echo $x echo $(( ++x )) echo $x echo $(( ++7 )) echo $(( 7-- )) echo $(( --x=7 )) echo $(( ++x=7 )) echo $(( x++=7 )) echo $(( x--=7 )) echo $x echo $(( +7 )) echo $(( -7 )) echo $(( ++7 )) echo $(( --7 )) x=4 y=7 (( x=8 , y=12 )) echo $x $y # should be an error (( x=9 y=41 )) # These are errors unset b echo $((a b)) ((a b)) n=42 printf "%d\n" $n printf "%i\n" $n echo $(( 8#$(printf "%o\n" $n) )) printf "%u\n" $n echo $(( 16#$(printf "%x\n" $n) )) echo $(( 16#$(printf "%X\n" $n) )) --- NEW FILE: read2.sub --- a=4 read -t 2 a echo $? echo $a sleep 5 | read -t 1 a echo $? echo $a read -t -3 a echo $? echo $a # the above should all time out echo abcde | { read -t 2 a echo $a } --- NEW FILE: redir3.in1 --- ab cd --- NEW FILE: redir3.in2 --- root daemon --- NEW FILE: nquote3.right --- argv[1] = <uv^A^A> argv[1] = <uv^A^A> argv[1] = <uv^A> argv[1] = <uv^A> argv[1] = <^Ab> argv[1] = <^Ab> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <uv^Aw^Axy> argv[1] = <uv^A> argv[1] = <uv^A> argv[1] = <^Awx> argv[1] = <^Awx> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <uv^Aw^Axy> argv[1] = <uv^A> argv[1] = <uv^A> argv[1] = <^Awx> argv[1] = <^Awx> argv[1] = <uv^A> argv[1] = <uv^A> argv[1] = <^Awx> argv[1] = <^Awx> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <uv^Aw^Axy> argv[1] = <uv^Aw^Axy> argv[1] = <uv^A> argv[1] = <uv^A> argv[1] = <^Awx> argv[1] = <^Awx> argv[1] = <uv^A> argv[2] = <uv^Aw> argv[1] = <uv^A> argv[2] = <uv^Aw> argv[1] = <^Awx> argv[2] = <w^Axy> argv[1] = <^Awx> argv[2] = <w^Axy> argv[1] = <wx> argv[2] = <xy> argv[1] = <uv^A^Awx> argv[2] = <uv^Aw^Axy> argv[1] = <uv^A> argv[2] = <uv^Aw> argv[1] = <uv^A> argv[2] = <uv^Aw> argv[1] = <^Awx> argv[2] = <w^Axy> argv[1] = <^Awx> argv[2] = <w^Axy> argv[1] = <wx> argv[2] = <xy> argv[1] = <uv^A^Awx> argv[2] = <uv^Aw^Axy> --- NEW FILE: input-line.sub --- read line echo line read by $0 was \`$line\' --- NEW FILE: redir3.sub --- read line1 echo read line1 \"$line1\" exec 4<./redir3.in2 exec 5<&0 exec 0<&4 read line2 echo read line2 \"$line2\" exec 0<&5 read line3 echo read line3 \"$line3\" exec 0<&4 read line4 echo read line4 \"$line4\" exec 4<&- --- NEW FILE: read.right --- a. -a-b- -a-b- -a b- -a b- -a-b\- -a b\- -\-a b\- -\ a b\- -\-a b\- -\ a b\- argv[1] = <^A> argv[1] = <^A> argv[1] = <^?> argv[1] = <^?> argv[1] = <abcd> 1: x[A] y[B] z[] 1a: 2: x[A B] [A B ] [ A B ] ==aa== ==== ==== argv[1] = < foo> argv[1] = < foo> argv[1] = <foo> argv[1] = < foo> argv[1] = <foo> argv[1] = <foo> argv[1] = < foo> a = abcdefg a = xyz a = -xyz 123- a = abc 1 4 1 4 ./read2.sub: line 13: read: -3: invalid timeout specification 1 4 abcde ./read3.sub: line 4: read: -1: invalid number abc ab # while read -u 3 var do echo "$var" done 3<$0 --- NEW FILE: nquote1.tests --- a=$'a\001b' set $a b=$a c=$1 d="$1" e=$'uv\001\001wx' recho a $a ${#a} recho 1 $1 ${#1} recho b $b ${#b} recho c $c ${#c} recho d $d ${#d} recho a ${a} ${#a} recho 1 ${1} ${#1} recho b ${b} ${#b} recho c ${c} ${#c} recho d ${d} ${#d} recho a "$a" ${#a} recho 1 "$1" ${#1} recho b "$b" ${#b} recho c "$c" ${#c} recho d "$d" ${#d} recho a "${a}" ${#a} recho 1 "${1}" ${#1} recho b "${b}" ${#b} recho c "${c}" ${#c} recho d "${d}" ${#d} set $e recho e1 ${e:1:3} recho e2 "${e:1:3}" recho e3 ${1:1:3} recho e4 "${1:1:3}" arr[0]=$e arr[1]=$e recho a1 ${arr:0:4} recho a2 "${arr:0:4}" recho a3 ${arr[@]:0:2} recho a4 "${arr[@]:0:2}" set $e $e recho p1 ${@:1:2} recho p2 "${@:1:2}" recho p1 ${*:1:2} recho p2 "${*:1:2}" recho $e recho 'uvwx' f='uvwx' recho $f echo -en "\01" | cat -v echo huhu() { echo "$1"; }; huhu $(echo -en "\01") | cat -v huhu $(echo -en "\02") | cat -v f=$'uv\001w\001xy' set $f $f recho f1 ${f:1:3} recho f2 "${f:1:3}" arr[0]=$f arr[1]=$f recho a1 ${arr:0:4} recho a2 "${arr:0:4}" recho a3 ${arr[0]:0:4} recho a4 "${arr[0]:0:4}" recho e1 ${f:0:4} recho e2 "${f:0:4}" recho d1 ${1:2:2} recho d2 "${1:2:2}" recho @1 ${@:1:2} recho @2 "${@:1:2}" --- NEW FILE: run-exp-tests --- ${THIS_SH} ./exp-tests | grep -v '^expect' > /tmp/xx diff /tmp/xx exp.right && rm -f /tmp/xx --- NEW FILE: new-exp3.sub --- : # Set up some dummy variables beginning with _Q _QUANTITY= _QUOTA= _QUOTE= _QUILL= _QUEST= _QUART= recho ${!_Q*} IFS="-$IFS" recho ${!_Q*} recho "${!_Q*}" recho ${!_Y*} recho "${!_Q* }" IFS=$' \t\n' set a b c d e f g h i j k l m n o p recho ${!1*} recho ${!@*} --- NEW FILE: exp.right --- argv[1] = <^A> argv[1] = <^A> argv[1] = <^B> argv[1] = <^B> argv[1] = <^A> argv[1] = <^B> argv[1] = <abcdefgh> argv[1] = <abcdefgh> argv[1] = <abcdefgh> argv[1] = <abcdefgh> argv[1] = <abcd> argv[1] = <abcd> argv[1] = < > argv[1] = <--> argv[1] = <> argv[1] = <> argv[1] = <> argv[1] = <> argv[1] = <> argv[1] = <> argv[1] = <abc> argv[1] = <abc> argv[1] = <abc> argv[1] = <abc> argv[1] = <abcdef> argv[1] = <abcdef> argv[1] = <^A> argv[1] = <^B> argv[1] = <^A> argv[1] = <^B> argv[1] = <^A> argv[1] = <^B> argv[1] = <> argv[1] = <> argv[1] = <> argv[1] = <Hello world!> argv[1] = <`> argv[1] = <"> argv[1] = <\^A> argv[1] = <\$> argv[1] = <\\> argv[1] = <a> argv[2] = <b> argv[1] = <^A> argv[2] = <^B> argv[1] = <**> argv[1] = <\.\./*/> argv[1] = <^A^B^A^B> argv[1] = <^A^A> argv[1] = <^A^B> argv[1] = <^A^A^B> argv[1] = < abc> argv[2] = <def> argv[3] = <ghi> argv[4] = <jkl > argv[1] = < abc> argv[2] = <def> argv[3] = <ghi> argv[4] = <jkl > argv[1] = <--abc> argv[2] = <def> argv[3] = <ghi> argv[4] = <jkl--> argv[1] = <a b> argv[2] = <cd> argv[3] = <ef> argv[4] = <gh> argv[1] = <a b> argv[2] = <cd> argv[3] = <ef> argv[4] = <gh> argv[1] = <a b> argv[2] = <cd> argv[3] = <ef> argv[4] = <gh> argv[1] = < > argv[1] = < - > argv[1] = </^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/> argv[1] = <foo bar> argv[1] = <foo> argv[2] = <bar> argv[1] = <abc> argv[1] = <abc> argv[1] = <posix> argv[1] = <10> argv[1] = <file.o> argv[1] = <posix> argv[1] = </src/cmd> argv[1] = <three> argv[1] = <abcdef> argv[1] = <abcdef> argv[1] = <abcdef> argv[1] = <abcdef> argv[1] = <\$x> argv[1] = <$x> argv[1] = <\$x> argv[1] = <abc> argv[2] = <def> argv[3] = <ghi> argv[4] = <jkl> argv[1] = <abc def ghi jkl> argv[1] = <abc:def ghi:jkl> argv[1] = <abc> argv[2] = <def ghi> argv[3] = <jkl> argv[1] = <xxabc> argv[2] = <def ghi> argv[3] = <jklyy> argv[1] = <abc> argv[2] = <def ghi> argv[3] = <jklabc> argv[4] = <def ghi> argv[5] = <jkl> argv[1] = <abcdef> argv[1] = <bar> argv[2] = <> argv[3] = <xyz> argv[4] = <> argv[5] = <abc> argv[1] = <$foo> argv[1] = <10> argv[1] = <newline expected> argv[1] = <got it> argv[1] = <got it> argv[1] = <one> argv[2] = <three> argv[3] = <five> argv[1] = <5> argv[2] = <5> argv[1] = <3> argv[1] = <1> argv[1] = <1> argv[1] = <5> argv[1] = <5> argv[1] = <5> argv[1] = <5> argv[1] = <42> argv[1] = <26> argv[1] = <\> argv[1] = <~> argv[1] = <a> argv[2] = <b> argv[3] = <c> argv[4] = <d> argv[5] = <e> --- NEW FILE: array-at-star --- # test the expansion of ${array[@]} and ${array[*]}, both quoted and # unquoted. the expansions should be exactly analogous to the # expansions of $@ and $* quoted and unquoted A=(a b) recho "${A[*]}" # If IFS is null, the parameters are joined without separators IFS='' recho "${A[*]}" # If IFS is unset, the parameters are separated by spaces unset IFS recho "${A[*]}" recho "${A[@]}" recho ${A[@]} IFS='/' A=(bob 'tom dick harry' joe) set ${A[*]} recho $# recho $1 recho $2 recho $3 A=(bob 'tom dick harry' joe) set ${A[*]} recho $# recho $1 recho $2 recho $3 A=(bob 'tom dick harry' joe) set ${A[@]} recho $# recho $1 recho $2 recho $3 A=(bob 'tom dick harry' joe) set ${A[@]} recho $# recho $1 recho $2 recho $3 # according to POSIX.2, unquoted $* should expand to multiple words if # $IFS is null, just like unquoted $@ IFS='' A=(bob 'tom dick harry' joe) set "${A[*]}" recho $# recho $1 recho $2 recho $3 A=(bob 'tom dick harry' joe) set ${A[*]} recho $# recho $1 recho $2 recho $3 A=(bob 'tom dick harry' joe) set ${A[@]} recho $# recho $1 recho $2 recho $3 # if IFS is unset, the individual positional parameters are split on # " \t\n" if $* or $@ are unquoted unset IFS A=(bob 'tom dick harry' joe) set ${A[*]} recho $# recho $1 recho $2 recho $3 A=(bob 'tom dick harry' joe) set ${A[@]} recho $# recho $1 recho $2 recho $3 # but not for "$@" or "$*" A=(bob 'tom dick harry' joe) set "${A[*]}" recho $# recho $1 recho $2 recho $3 A=(bob 'tom dick harry' joe) set "${A[@]}" recho $# recho $1 recho $2 recho $3 # these should both expand the value of A to multiple words A=(a b c d e) IFS="" recho ${A[@]} recho "${A[@]}" # this example is straight from the POSIX.2 rationale and adapted to arrays A=(foo bar bam) recho "${A[@]}" recho "${A[*]}" unset IFS recho "${A[@]}" recho ${A[@]} recho "${A[*]}" --- NEW FILE: builtins.tests --- # tests for miscellaneous builtins not tested elsewhere set +p set +o posix ulimit -c 0 2>/dev/null # alias/unalias tests unalias -a # this should return success, according to POSIX.2 alias echo alias: $? alias foo=bar unalias foo # this had better return success, according to POSIX.2 alias echo alias: $? # check that break breaks loops for i in a b c; do echo $i; break; echo bad-$i; done echo end-1 for i in a b c; do echo $i; break 1; echo bad-$i; done echo end-2 for i in a b c; do for j in x y z; do echo $i:$j break echo bad-$i done echo end-$i done echo end-3 # check that break breaks nested loops for i in a b c; do for j in x y z; do echo $i:$j break 2 echo bad-$i done echo end-$i done echo end # check that continue continues loops for i in a b c; do echo $i; continue; echo bad-$i ; done echo end-1 for i in a b c; do echo $i; continue 1; echo bad-$i; done echo end-2 for i in a b c; do for j in x y z; do echo $i:$j continue echo bad-$i-$j done echo end-$i done echo end-3 # check that continue breaks out of nested loops for i in a b c; do for j in x y z; do echo $i:$j continue 2 echo bad-$i-$j done echo end-$i done echo end # check that `eval' re-evaluates arguments, but `builtin' and `command' do not AVAR='$BVAR' BVAR=foo echo $AVAR builtin echo $AVAR command echo $AVAR eval echo \$AVAR eval echo $AVAR # test out eval with a temp environment AVAR=bar eval echo \$AVAR BVAR=xxx eval echo $AVAR unset -v AVAR BVAR # test umask mask=$(umask) umask 022 umask umask -S umask -S u=rwx,g=rwx,o=rx >/dev/null # 002 umask umask -S umask -p umask -p -S umask 0 umask -S umask ${mask} # restore original mask # builtin/command without arguments should do nothing. maybe someday they will builtin command # test enable enable -ps enable -aps ; enable -nps enable -n test case "$(type -t test)" in builtin) echo oops -- enable -n test failed ;; *) echo enable -n test worked ;; esac enable test case "$(type -t test)" in builtin) echo enable test worked ;; *) echo oops -- enable test failed ;; esac # test options to exec (exec -a specialname ${THIS_SH} -c 'echo $0' ) (exec -l -a specialname ${THIS_SH} -c 'echo $0' ) # test `clean' environment. if /bin/sh is bash, and the script version of # printenv is run, there will be variables in the environment that bash # sets on startup. Also test code that prefixes argv[0] with a dash. (export FOO=BAR ; exec -c -l printenv ) | grep FOO (FOO=BAR exec -c printenv ) | grep FOO (export FOO=BAR ; exec printenv ) | grep FOO (FOO=BAR exec printenv ) | grep FOO # ok, forget everything about hashed commands hash -r hash # this had better succeed, since command -p guarantees we will find the # standard utilties command -p hash rm # check out source/. # sourcing a zero-length-file had better not be an error rm -f /tmp/zero-length-file cp /dev/null /tmp/zero-length-file . /tmp/zero-length-file echo $? rm /tmp/zero-length-file AVAR=AVAR . ./source1.sub AVAR=foo . ./source1.sub . ./source2.sub echo $? set -- a b c . ./source3.sub # make sure source with arguments does not change the shell's positional # parameters, but that the sourced file sees the arguments as its # positional parameters echo "$@" . ./source3.sub x y z echo "$@" # but if the sourced script sets the positional parameters explicitly, they # should be reflected in the calling shell's positional parameters. this # also tests one of the shopt options that controls source using $PATH to # find the script echo "$@" shopt -u sourcepath . source4.sub echo "$@" # this is complicated when the sourced scripts gets its own positional # parameters from arguments to `.' set -- a b c echo "$@" . source4.sub x y z echo "$@" # test out cd and $CDPATH ${THIS_SH} ./builtins1.sub # test behavior of `.' when given a non-existant file argument ${THIS_SH} ./source5.sub # in posix mode, assignment statements preceding special builtins are # reflected in the shell environment. `.' and `eval' need special-case # code. set -o posix echo $AVAR AVAR=foo . ./source1.sub echo $AVAR AVAR=AVAR echo $AVAR AVAR=foo eval echo \$AVAR echo $AVAR AVAR=AVAR echo $AVAR AVAR=foo : echo $AVAR set +o posix # but assignment statements preceding `export' are always reflected in # the environment foo="" export foo declare -p foo unset foo # assignment statements preceding `declare' should be displayed correctly, # but not persist after the command FOO='$$' declare -p FOO declare -p FOO unset FOO # except for `declare -x', which should be equivalent to `export' FOO='$$' declare -x FOO declare -p FOO unset FOO # test out kill -l. bash versions prior to 2.01 did `kill -l num' wrong sigone=$(kill -l | sed -n 's:^ 1) *\([^ ]*\)[ ].*$:\1:p') case "$(kill -l 1)" in ${sigone/SIG/}) echo ok;; *) echo oops -- kill -l failure;; esac # kill -l and trap -l should display exactly the same output sigonea=$(trap -l | sed -n 's:^ 1) *\([^ ]*\)[ ].*$:\1:p') if [ "$sigone" != "$sigonea" ]; then echo oops -- kill -l and trap -l differ fi # POSIX.2 says that exit statuses > 128 are mapped to signal names by # subtracting 128 so you can find out what signal killed a process case "$(kill -l $(( 128 + 1)) )" in ${sigone/SIG/}) echo ok;; *) echo oops -- kill -l 129 failure;; esac # out-of-range signal numbers should report the argument in the error # message, not 128 less than the argument kill -l 4096 # kill -l NAME should return the signal number kill -l ${sigone/SIG/} # test behavior of shopt xpg_echo ${THIS_SH} ./builtins2.sub # this must be last -- it is a fatal error exit status echo after bad exit --- NEW FILE: array2.right --- argv[1] = <a b> argv[1] = <ab> argv[1] = <a b> argv[1] = <a> argv[2] = <b> argv[1] = <a> argv[2] = <b> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <1> argv[1] = <bobtom dick harryjoe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <5> argv[1] = <bob> argv[1] = <tom> argv[1] = <dick> argv[1] = <5> argv[1] = <bob> argv[1] = <tom> argv[1] = <dick> argv[1] = <1> argv[1] = <bob> argv[2] = <tom> argv[3] = <dick> argv[4] = <harry> argv[5] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom> argv[2] = <dick> argv[3] = <harry> argv[1] = <joe> argv[1] = <a> argv[2] = <b> argv[3] = <c> argv[4] = <d> argv[5] = <e> argv[1] = <a> argv[2] = <b> argv[3] = <c> argv[4] = <d> argv[5] = <e> argv[1] = <foo> argv[2] = <bar> argv[3] = <bam> argv[1] = <foobarbam> argv[1] = <foo> argv[2] = <bar> argv[3] = <bam> argv[1] = <foo> argv[2] = <bar> argv[3] = <bam> argv[1] = <foo bar bam> --- NEW FILE: nquote2.right --- argv[1] = <a^Ab> argv[1] = <uv^A^Awx> argv[1] = <aAb> argv[1] = <aAb> argv[1] = <uvA^Awx> argv[1] = <uvA^Awx> argv[1] = <a^AB> argv[1] = <a^AB> argv[1] = <uv^A^AWx> argv[1] = <uv^A^AWx> argv[1] = <aAb> argv[1] = <aAb> argv[1] = <uvAAwx> argv[1] = <uvAAwx> argv[1] = <a^AB> argv[1] = <a^AB> argv[1] = <uv^A^AWx> argv[1] = <uv^A^AWx> argv[1] = <uvA^Awx> argv[2] = <uvA^Awx> argv[1] = <uvA^Awx> argv[2] = <uvA^Awx> argv[1] = <uv^A^AWx> argv[2] = <uv^A^AWx> argv[1] = <uv^A^AWx> argv[2] = <uv^A^AWx> argv[1] = <uvAAwx> argv[2] = <uvAAwx> argv[1] = <uvAAwx> argv[2] = <uvAAwx> argv[1] = <uv^A^AWx> argv[2] = <uv^A^AWx> argv[1] = <uv^A^AWx> argv[2] = <uv^A^AWx> argv[1] = <a^Ab> argv[1] = <uv^A^Awx> argv[1] = <aAb> argv[1] = <aAb> argv[1] = <uvA^Awx> argv[1] = <uvA^Awx> argv[1] = <a^AB> argv[1] = <a^AB> argv[1] = <uv^A^AWx> argv[1] = <uv^A^AWx> argv[1] = <aAb> argv[1] = <aAb> argv[1] = <uvAAwx> argv[1] = <uvAAwx> argv[1] = <a^AB> argv[1] = <a^AB> argv[1] = <uv^A^AWx> argv[1] = <uv^A^AWx> argv[1] = <aAb> argv[2] = <uvA^Awx> argv[1] = <aAb> argv[2] = <uvA^Awx> argv[1] = <a^AB> argv[2] = <uv^A^Awx> argv[1] = <a^AB> argv[2] = <uv^A^Awx> argv[1] = <a^Ab> argv[2] = <uv^A^AWx> argv[1] = <a^Ab> argv[2] = <uv^A^AWx> argv[1] = <aAb> argv[2] = <uvAAwx> argv[1] = <aAb> argv[2] = <uvAAwx> argv[1] = <a^AB> argv[2] = <uv^A^Awx> argv[1] = <a^AB> argv[2] = <uv^A^Awx> argv[1] = <a^Ab> argv[2] = <uv^A^AWx> argv[1] = <a^Ab> argv[2] = <uv^A^AWx> --- NEW FILE: ifs.right --- a:b:c a:b:c a:b:c a b c d e a:b:c:d:e a b c d e a:b:c:d:e a:b:c:d:e a b c d e a b c d e --- NEW FILE: input-line.sh --- echo before calling input-line.sub ${THIS_SH} ./input-line.sub this line for input-line.sub echo finished with input-line.sub --- NEW FILE: read4.sub --- while read -u 3 var do echo "$var" done 3<$0 --- NEW FILE: dollar-at-star --- # first, let's start with the basics recho "$@" recho "$*" recho $@ recho $* set a b recho "$*" # If IFS is null, the parameters are joined without separators IFS='' recho "$*" # If IFS is unset, the parameters are separated by spaces unset IFS recho "${*}" recho "$@" recho $@ IFS='/' set bob 'tom dick harry' joe set $* recho $# recho $1 recho $2 recho $3 set bob 'tom dick harry' joe set ${*} recho $# recho $1 recho $2 recho $3 set bob 'tom dick harry' joe set $@ recho $# recho $1 recho $2 recho $3 set bob 'tom dick harry' joe set ${@} recho $# recho $1 recho $2 recho $3 # according to POSIX.2, unquoted $* should expand to multiple words if # $IFS is null, just like unquoted $@ IFS='' set bob 'tom dick harry' joe set $* recho $# recho $1 recho $2 recho $3 set bob 'tom dick harry' joe set $@ recho $# recho $1 recho $2 recho $3 # if IFS is unset, the individual positional parameters are split on # " \t\n" if $* or $@ are unquoted unset IFS set bob 'tom dick harry' joe set $* recho $# recho $1 recho $2 recho $3 set bob 'tom dick harry' joe set $@ recho $# recho $1 recho $2 recho $3 # but not for "$@" or "$*" set bob 'tom dick harry' joe set "$*" recho $# recho $1 recho $2 recho $3 set bob 'tom dick harry' joe set "$@" recho $# recho $1 recho $2 recho $3 # POSIX.2 says these should both expand the positional parameters # to multiple words set a b c d e IFS="" recho $@ recho "$@" # this example is straight from the POSIX.2 rationale set foo bar bam recho "$@" recho "$*" unset IFS recho "$@" recho $@ recho "$*" IFS=: # special variables set -- 1 2 3 4 5 6 7 8 9 10 bar=${*} foo=$* echo foo = "$foo" echo bar = "$bar" foo1=$@ bar1=${@} echo foo1 = "$foo1" echo bar1 = "$bar1" foo2="$*" bar2="${*}" echo foo2 = "$foo2" echo bar2 = "$bar2" eval foo3='$*' bar3='${*}' echo foo3 = "$foo3" echo bar3 = "$bar3" case $* in *\:*) echo ok 1;; *) echo bad 1;; esac case $@ in *\:*) echo bad 2;; *) echo ok 2;; esac case "$*" in *\:*) echo ok 3;; *) echo bad 3;; esac case "$@" in *\:*) echo bad 4;; *) echo ok 4;; esac IFS=$' \t\n' bar=${*} foo=$* echo foo = "$foo" echo bar = "$bar" foo1=$@ bar1=${@} echo foo1 = "$foo1" echo bar1 = "$bar1" foo2="$*" bar2="${*}" echo foo2 = "$foo2" echo bar2 = "$bar2" eval foo3='$*' bar3='${*}' echo foo3 = "$foo3" echo bar3 = "$bar3" case $* in *\ *) echo ok 1;; *) echo bad 1;; esac case $@ in *\ *) echo ok 2;; *) echo bad 2;; esac case "$*" in *\ *) echo ok 3;; *) echo bad 3;; esac case "$@" in *\ *) echo ok 4;; *) echo bad 4;; esac exit 0 --- NEW FILE: getopts4.sub --- aflag= bflag= while getopts :ab: name "$@" do case $name in a) aflag=1 ;; b) bflag=1 bval=$OPTARG;; :) echo $0: error: option \`$OPTARG\' requires an argument echo Usage: $0 [-a] [-b value] args exit 2;; ?) echo $0: error: illegal option character \`$OPTARG\' echo Usage: $0 [-a] [-b value] args exit 2;; esac done if [ ! -z "$aflag" ] ; then echo -a specified ; fi if [ ! -z "$bflag" ] ; then echo -b $bval specified ; fi if [ "$OPTIND" -gt 1 ] then shift $(( $OPTIND - 1 )) fi echo remaining args: "$*" exit 0 --- NEW FILE: run-type --- ${THIS_SH} ./type.tests > /tmp/xx 2>&1 diff /tmp/xx type.right && rm -f /tmp/xx --- NEW FILE: set-e-test --- if : ; then set -e N=95 while :; do # expr returns 1 if expression is null or 0 set +e N_MOD_100=`expr $N % 100` set -e echo $N_MOD_100 N=`expr $N + 1` if [ $N -eq 110 ]; then break fi done set +e fi ( set -e false echo bad ) echo $? x=$( set -e false echo bad ) echo $? $x # command subst should not inherit -e set -e echo $(false; echo ok) if set +e then false fi echo hi set -e # a failing command in the compound list following a while, until, or # if should not cause the shell to exit while false; do echo hi done echo while succeeded x=1 until (( x == 4 )); do x=4 done echo until succeeded: $x if false; then echo oops fi echo if succeeded # failing commands that are part of an AND or OR list should not # cause the shell to exit false && echo AND list failed echo AND list succeeded false || echo OR list succeeded ! false echo ! succeeded # make sure eval preserves the state of the -e flag and `!' reserved word set -e if eval false; then echo oops fi echo eval succeeded ! eval false echo ! eval succeeded -- 1 ! eval '(exit 5)' echo ! eval succeeded -- 2 --- NEW FILE: dstack2.right --- expect ~1 ~1 /usr / /tmp /usr / /tmp /usr / these lines should be the same /tmp /tmp /tmp these lines should be the same /usr /usr /usr these lines should be the same / / / these lines should be the same /tmp /tmp /tmp these lines should be the same /usr /usr /usr 1 /usr these lines should be the same / / / --- NEW FILE: run-read --- ${THIS_SH} ./read.tests > /tmp/xx 2>&1 diff /tmp/xx read.right && rm -f /tmp/xx --- NEW FILE: run-getopts --- ${THIS_SH} ./getopts.tests > /tmp/xx 2>&1 diff /tmp/xx getopts.right && rm -f /tmp/xx --- NEW FILE: run-histexpand --- echo "warning: all of these tests will fail if history has not been compiled" >&2 echo "warning: into the shell" >&2 ${THIS_SH} ./histexp.tests > /tmp/xx 2>&1 diff /tmp/xx histexp.right && rm -f /tmp/xx --- NEW FILE: exec.right --- before exec1.sub: one two three calling exec1.sub aa bb cc dd ee after exec1.sub with args: 0 after exec1.sub without args: 0 ./execscript: line 20: notthere: command not found 127 notthere: notthere: No such file or directory 127 /bin/sh: /bin/sh: cannot execute binary file 126 ./execscript: line 32: /: is a directory 126 /: /: cannot execute binary file 126 ./execscript: line 39: .: /: is a directory 1 127 0 this is bashenv ./exec3.sub: line 3: /tmp/bash-notthere: No such file or directory ./exec3.sub: line 3: exec: /tmp/bash-notthere: cannot execute: No such file or directory 126 ./execscript: line 61: notthere: No such file or directory 127 ./execscript: line 64: notthere: No such file or directory 127 ./execscript: line 67: notthere: No such file or directory 127 this is sh this is sh unset ok 5 ./exec5.sub: line 4: exec: bash-notthere: not found 127 this is ohio-state 0 1 1 0 42 42 0 1 1 0 0 1 0 1 --- NEW FILE: heredoc.right --- there one - alpha two - beta three - gamma hi\ there$a stuff hi\ there EO\ F hi hi tab 1 tab 2 tab 3 abc def ghi jkl mno fff is a function fff () { ed /tmp/foo >/dev/null <<ENDOFINPUT /^name/d w q ENDOFINPUT aa=1 } fff is a function fff () { ed /tmp/foo >/dev/null <<ENDOFINPUT /^name/d w q ENDOFINPUT aa=1 } hi there --- NEW FILE: ifs.tests --- OIFS="$IFS" IFS=":$IFS" eval foo="a:b:c" IFS="$OIFS" echo $foo OIFS=$IFS IFS=":$IFS" foo=$(echo a:b:c) IFS=$OIFS for i in $foo do echo $i done OIFS=$IFS IFS=":$IFS" foo=`echo a:b:c` IFS=$OIFS for i in $foo do echo $i done DEFIFS=$' \t\n' # local copy of IFS that shadows global version function f { typeset IFS=: echo $1 } function ff { echo $1 } f a:b:c:d:e x=a:b:c:d:e echo $x IFS=: ff a:b:c:d:e echo $x # doesn't get word split IFS=$DEFIFS # variable assignment doesn't use new value for word splitting IFS=: echo $x # but does this time because of the eval IFS=: eval echo \$x # in posix mode, assignments preceding special builtins and functions are global set -o posix IFS=: export x echo $x IFS="$DEFIFS" --- NEW FILE: dollar.right --- argv[1] = <> argv[1] = <a b> argv[1] = <ab> argv[1] = <a b> argv[1] = <a> argv[2] = <b> argv[1] = <a> argv[2] = <b> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom dick harry> argv[1] = <joe> argv[1] = <5> argv[1] = <bob> argv[1] = <tom> argv[1] = <dick> argv[1] = <5> argv[1] = <bob> argv[1] = <tom> argv[1] = <dick> argv[1] = <1> argv[1] = <bob> argv[2] = <tom> argv[3] = <dick> argv[4] = <harry> argv[5] = <joe> argv[1] = <3> argv[1] = <bob> argv[1] = <tom> argv[2] = <dick> argv[3] = <harry> argv[1] = <joe> argv[1] = <a> argv[2] = <b> argv[3] = <c> argv[4] = <d> argv[5] = <e> argv[1] = <a> argv[2] = <b> argv[3] = <c> argv[4] = <d> argv[5] = <e> argv[1] = <foo> argv[2] = <bar> argv[3] = <bam> argv[1] = <foobarbam> argv[1] = <foo> argv[2] = <bar> argv[3] = <bam> argv[1] = <foo> argv[2] = <bar> argv[3] = <bam> argv[1] = <foo bar bam> foo = 1:2:3:4:5:6:7:8:9:10 bar = 1:2:3:4:5:6:7:8:9:10 foo1 = 1 2 3 4 5 6 7 8 9 10 bar1 = 1 2 3 4 5 6 7 8 9 10 foo2 = 1:2:3:4:5:6:7:8:9:10 bar2 = 1:2:3:4:5:6:7:8:9:10 foo3 = 1:2:3:4:5:6:7:8:9:10 bar3 = 1:2:3:4:5:6:7:8:9:10 ok 1 ok 2 ok 3 ok 4 foo = 1 2 3 4 5 6 7 8 9 10 bar = 1 2 3 4 5 6 7 8 9 10 foo1 = 1 2 3 4 5 6 7 8 9 10 bar1 = 1 2 3 4 5 6 7 8 9 10 foo2 = 1 2 3 4 5 6 7 8 9 10 bar2 = 1 2 3 4 5 6 7 8 9 10 foo3 = 1 2 3 4 5 6 7 8 9 10 bar3 = 1 2 3 4 5 6 7 8 9 10 ok 1 ok 2 ok 3 ok 4 --- NEW FILE: run-cond --- echo "warning: all of these tests will fail if the conditional command has not" >&2 echo "warning: been compiled into the shell" >&2 echo "warning: some of these tests will fail if extended pattern matching has not" >&2 echo "warning: been compiled into the shell" >&2 ${THIS_SH} ./cond.tests > /tmp/xx 2>&1 diff /tmp/xx cond.right && rm -f /tmp/xx --- NEW FILE: run-rhs-exp --- ${THIS_SH} ./rhs-exp.tests 2>&1 > /tmp/xx diff /tmp/xx rhs-exp.right && rm -f /tmp/xx --- NEW FILE: run-more-exp --- ${THIS_SH} ./more-exp.tests 2>&1 | grep -v '^expect' > /tmp/xx diff /tmp/xx more-exp.right && rm -f /tmp/xx --- NEW FILE: new-exp2.sub --- export LC_ALL=C export LANG=C # test out the new $(< filename) code # it should be exactly equivalent to $(cat filename) FILENAME=/tmp/bashtmp.x$$ trap 'rm -f $FILENAME' 0 cat >$FILENAME << EOF line 1 line 2 line 3 EOF LINES1=$(cat $FILENAME) LINES2=$(< $FILENAME) if [[ $LINES1 != $LINES2 ]]; then echo 'whoops: $(< filename) failed' fi LINES2=$(< /tmp/bashtmp.x*) if [[ $LINES1 != $LINES2 ]]; then echo 'whoops: $(< filename) with glob expansion failed' fi # but the glob expansion in the redirection should fail in posix mode set -o posix LINES2=$(< /tmp/bashtmp.x*) set +o posix # now see what happens when we try it with a non-existant file LINES3=$(< /tmp/redir-notthere) echo $? --- NEW FILE: redir.tests --- export LC_ALL=C export LANG=C # catch-all for remaining untested redirection stuff set +o posix echo abc > /tmp/redir-test cat /tmp/redir-test set -o noclobber #this should be an error echo def > /tmp/redir-test cat /tmp/redir-test # but this should succeed echo def > /tmp/redir-test-2 cat /tmp/redir-test-2 # and so should this echo def >| /tmp/redir-test cat /tmp/redir-test set +o noclobber rm /tmp/redir-test /tmp/redir-test-2 # this should be an error z="a b" cat < $z echo "Point 1" exec 3</etc/passwd exec 4>/tmp/bash-a exec 5>/tmp/bash-b echo "Point 2" echo to a 1>&4 echo to b 1>&5 cat /tmp/bash-a cat /tmp/bash-b exec 11</dev/null echo "Point 3" echo to a 1>&4 echo to b 1>&5 cat /tmp/bash-a cat /tmp/bash-b exec 11<&- echo "Point 4" exec 6<>/tmp/bash-c echo to c 1>&6 cat /tmp/bash-c echo "Point 5" rm -f /tmp/bash-a /tmp/bash-b /tmp/bash-c # # Test the effect of input buffering on the shell's input # ${THIS_SH} < redir1.sub # more open, close, duplicate file descriptors ${THIS_SH} ./redir3.sub < ./redir3.in1 # still more redirections ${THIS_SH} ./redir4.sub < redir4.in1 # various forms of null redirection testf() { if [ -f "$1" ]; then rm -f "$1" else echo oops -- $1 not found fi } > /tmp/null-redir-a testf /tmp/null-redir-a $EXIT > /tmp/null-redir-b testf /tmp/null-redir-b ( > /tmp/null-redir-c ) testf /tmp/null-redir-c $EXIT > /tmp/null-redir-d & wait testf /tmp/null-redir-d exit 3 | $EXIT > /tmp/null-redir-e echo $? -- ${PIPESTATUS[@]} testf /tmp/null-redir-e exit 4 | > /tmp/null-redir-f echo $? -- ${PIPESTATUS[@]} testf /tmp/null-redir-f > /tmp/null-redir-g & wait testf /tmp/null-redir-g exec >/tmp/null-redir-h & wait testf /tmp/null-redir-h # make sure async commands don't get /dev/null as stdin when an explicit # input redirection is supplied for x in 1 2 3; do { read line ; echo $line ; } & wait { read line ; echo $line ; } & wait done << EOF ab cd ef gh ij kl EOF # make sure async commands get /dev/null as stdin in the absence of any # input redirection /bin/cat & wait echo $? # make sure that loops work OK with here documents and are not run in # subshells while read line; do echo $line l2=$line done << EOF ab cd EOF echo $l2 # These should not echo anything -- bug in versions before 2.04 ( ( echo hello 1>&3 ) 3>&1 ) >/dev/null 2>&1 ( ( echo hello 1>&3 ) 3>&1 ) >/dev/null 2>&1 | cat # in posix mode, non-interactive shells are not allowed to perform # filename expansion on input redirections, even if they expand to # a single filename set -o posix cat < redir1.* # test ksh93 dup-and-close (move fd) redirections ${THIS_SH} ./redir5.sub --- NEW FILE: extglob2.tests --- # # More ksh-like extended globbing tests, cribbed from zsh-3.1.5 # shopt -s extglob failed=0 while read res str pat; do [[ $res = '#' ]] && continue [[ $str = ${pat} ]] ts=$? [[ $1 = -q ]] || echo "$ts: [[ $str = $pat ]]" if [[ ( $ts -gt 0 && $res = t) || ($ts -eq 0 && $res = f) ]]; then echo "Test failed: [[ $str = $pat ]]" (( failed += 1 )) fi done <<EOT t fofo *(f*(o)) t ffo *(f*(o)) t foooofo *(f*(o)) t foooofof *(f*(o)) t fooofoofofooo *(f*(o)) f foooofof *(f+(o)) f xfoooofof *(f*(o)) f foooofofx *(f*(o)) t ofxoofxo *(*(of*(o)x)o) f ofooofoofofooo *(f*(o)) t foooxfooxfoxfooox *(f*(o)x) f foooxfooxofoxfooox *(f*(o)x) t foooxfooxfxfooox *(f*(o)x) t ofxoofxo *(*(of*(o)x)o) t ofoooxoofxo *(*(of*(o)x)o) t ofoooxoofxoofoooxoofxo *(*(of*(o)x)o) t ofoooxoofxoofoooxoofxoo *(*(of*(o)x)o) f ofoooxoofxoofoooxoofxofo *(*(of*(o)x)o) t ofoooxoofxoofoooxoofxooofxofxo *(*(of*(o)x)o) t aac *(@(a))a@(c) t ac *(@(a))a@(c) f c *(@(a))a@(c) t aaac *(@(a))a@(c) f baaac *(@(a))a@(c) t abcd ?@(a|b)*@(c)d t abcd @(ab|a*@(b))*(c)d t acd @(ab|a*(b))*(c)d t abbcd @(ab|a*(b))*(c)d t effgz @(b+(c)d|e*(f)g?|?(h)i@(j|k)) t efgz @(b+(c)d|e*(f)g?|?(h)i@(j|k)) t egz @(b+(c)d|e*(f)g?|?(h)i@(j|k)) t egzefffgzbcdij *(b+(c)d|e*(f)g?|?(h)i@(j|k)) f egz @(b+(c)d|e+(f)g?|?(h)i@(j|k)) t ofoofo *(of+(o)) t oxfoxoxfox *(oxf+(ox)) f oxfoxfox *(oxf+(ox)) t ofoofo *(of+(o)|f) # The following is supposed to match only as fo+ofo+ofo t foofoofo @(foo|f|fo)*(f|of+(o)) t oofooofo *(of|oof+(o)) t fffooofoooooffoofffooofff *(*(f)*(o)) # The following tests backtracking in alternation matches t fofoofoofofoo *(fo|foo) # Exclusion t foo !(x) t foo !(x)* f foo !(foo) t foo !(foo)* t foobar !(foo) t foobar !(foo)* t moo.cow !(*.*).!(*.*) f mad.moo.cow !(*.*).!(*.*) f mucca.pazza mu!(*(c))?.pa!(*(z))? t fff !(f) t fff *(!(f)) t fff +(!(f)) t ooo !(f) t ooo *(!(f)) t ooo +(!(f)) t foo !(f) t foo *(!(f)) t foo +(!(f)) f f !(f) f f *(!(f)) f f +(!(f)) t foot @(!(z*)|*x) f zoot @(!(z*)|*x) t foox @(!(z*)|*x) t zoox @(!(z*)|*x) t foo *(!(foo)) f foob !(foo)b* t foobb !(foo)b* EOT echo "$failed tests failed." --- NEW FILE: exec5.sub --- # try exec'ing a command that cannot be found in $PATH shopt -s execfail exec bash-notthere # make sure we're still around echo $? # now we need to go away, but this should echo 'this is ohio-state' exec -a ohio-state ${THIS_SH} -c 'echo this is $0' --- NEW FILE: trap2.sub --- set +e trap 'echo ERRTRAP' ERR false false false echo after falses if ! false; then echo if negation ok fi ! false echo after negation while false; do echo while negation ok done echo after while ./trap2a.sub echo $(false ; echo command substitution) --- NEW FILE: func1.sub --- # # Test that redirections attached to shell functions are printed correctly. # This was a bug in all bash versions before bash-2.04. # f() { echo f-x echo f-y } >&2 type f export -f f ${THIS_SH} -c 'echo subshell; type f' f2() { echo f2-a f3() { echo f3-a echo f3-b } >&2 f3 } type f2 export -f f2 ${THIS_SH} -c 'echo subshell; type f2' f4() { echo f4-a f5() { echo f5-a echo f5-b } >&2 f5 } 2>&1 type f4 export -f f4 ${THIS_SH} -c 'echo subshell; type f4' testgrp() { echo testgrp-a { echo tg-x; echo tg-y; } >&2 echo testgrp-b } type testgrp export -f testgrp ${THIS_SH} -c 'echo subshell; type testgrp' --- NEW FILE: read1.sub --- a=7 echo 'abcdefg|xyz' | { read -d '|' a echo a = "${a-unset}" } echo xyz 123 | { read -d ' ' a echo a = "${a-unset}" } echo xyz 123 | { read -d $'\n' a echo a = -"${a-unset}"- } a=44 echo abcd | { read -d d a echo a = $a } exit 0 --- NEW FILE: glob1.sub --- # bash-2.01.1 failed this test FN=/tmp/bash-glob.$$ mkdir $FN cd $FN mkdir foo mkdir foobar touch foo/bar touch foobar/bar chmod 311 foo foobar echo f*/bar chmod 777 foo foobar cd / rm -rf $FN --- NEW FILE: trap1.sub --- # signals ignored at shell startup cannot be trapped or reset trap 'echo USR2' USR2 trap -p USR2 --- NEW FILE: redir1.sub --- # # Test the effect of input buffering on the shell's input # echo this is redir1.sub exec 0< redir2.sub echo BUG: after exec in redir1.sub --- NEW FILE: run-arith-for --- ${THIS_SH} ./arith-for.tests > /tmp/xx 2>&1 diff /tmp/xx arith-for.right && rm -f /tmp/xx --- NEW FILE: more-exp.right --- argv[1] = <aaa bbb ccc> argv[1] = <aaa bbb ccc> argv[1] = <baz:bar> argv[1] = <baz:bar> argv[1] = <aaa bbb ccc> argv[1] = <bar> argv[1] = <bar> argv[1] = <bar> argv[1] = <abcde> argv[1] = <abcde> argv[1] = <xyz> argv[1] = <a b> argv[2] = <c> argv[3] = <d> argv[4] = <e> argv[5] = <f> argv[1] = <a b> argv[1] = <a> argv[2] = <b> argv[1] = <a b> argv[2] = <c> argv[3] = <d> argv[4] = <e> argv[5] = <f> argv[1] = <a b> argv[2] = <c> argv[3] = <d> argv[4] = <e> argv[5] = <f> argv[1] = </usr/homes/chet> argv[1] = </usr/homes/chet> argv[1] = <~> argv[1] = <\~> argv[1] = <\ \~> argv[1] = <\ \ \~> argv[1] = </usr/homes/chet> argv[1] = </usr/homes/chet> argv[1] = </usr/homes/chet> argv[1] = <$HOME> argv[1] = <\ $HOME> argv[1] = <\ \ $HOME> argv[1] = <'bar'> argv[1] = <'bar'> argv[1] = <*@> argv[1] = <*@> argv[1] = <*@> argv[1] = <*@> argv[1] = <*@*> argv[1] = <*@*> argv[1] = <*@*> argv[1] = <*@*> argv[1] = <abcd> argv[1] = <efghijkl> argv[1] = <4> argv[2] = <2> argv[1] = <1> argv[1] = <bar> argv[1] = <2> argv[1] = <bar> argv[1] = <2> argv[1] = <4> argv[1] = <--\> argv[2] = <--> argv[1] = <--\^J--> argv[1] = <--+\> argv[2] = <+--> argv[1] = <--+\^J+--> argv[1] = <-+\> argv[2] = <+-\> argv[3] = <-> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <> argv[1] = <> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <xy> argv[1] = <> argv[1] = <> argv[1] = <x> argv[1] = <x> argv[1] = <> argv[1] = <x> argv[1] = <x> argv[1] = <x> argv[1] = <x> argv[1] = <^?> argv[1] = <^?> argv[1] = <x> argv[1] = <x> argv[1] = <> argv[2] = <abd> argv[3] = <x> argv[1] = <> argv[2] = <abd> argv[3] = <> argv[1] = <a,b,c,d,e,f> argv[1] = <a> argv[2] = <b> argv[3] = <c> argv[4] = <d> argv[5] = <e> argv[6] = <f> ./more-exp.tests: line 269: abc=def: command not found argv[1] = <a b c d e> argv[1] = <a> argv[2] = <b> argv[3] = <c> argv[4] = <d> argv[5] = <e> argv[1] = <foo)> argv[1] = <a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\\a> argv[1] = <a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\\a> argv[1] = <a> argv[1] = <a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\a> argv[1] = <$a> argv[1] = <\foo> argv[1] = <$a> argv[1] = <\foo> argv[1] = <\$a> argv[1] = <\\$a> argv[1] = <a> argv[1] = <a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\a> argv[1] = <\a> argv[1] = <G> argv[2] = <{> argv[3] = <I> argv[4] = <K> argv[5] = <}> argv[1] = <hi> argv[2] = <K> argv[3] = <}> argv[1] = <a*> Number of args: 0 <${*-x}>: <x> <${@-x}>: <x> Number of args: 1 <${*-x}>: <> <${@-x}>: <> Number of args: 2 <${*-x}>: < > <${@-x}>: < > argv[1] = <5> argv[1] = <5> argv[1] = <5> argv[1] = <5> argv[1] = <5> argv[1] = <0> argv[1] = <0> argv[1] = <0> argv[1] = <0> argv[1] = <0> argv[1] = <0> argv[1] = <posparams> argv[1] = <posparams> argv[1] = <2> argv[1] = <0> argv[1] = <0> argv[1] = <1> argv[1] = <5> argv[1] = <5> argv[1] = <0> ./more-exp.tests: line 420: ${#:}: bad substitution ./more-exp.tests: line 422: ${#/}: bad substitution ./more-exp.tests: line 424: ${#%}: bad substitution ./more-exp.tests: line 426: ${#=}: bad substitution ./more-exp.tests: line 428: ${#+}: bad substitution ./more-exp.tests: line 430: ${#1xyz}: bad substitution ./more-exp.tests: line 433: #: %: syntax error: operand expected (error token is "%") argv[1] = <0> argv[1] = <a+b> argv[1] = <+> argv[1] = <+> argv[1] = <+> argv[1] = <G { I > argv[2] = <K> argv[3] = <}> argv[1] = <hi> argv[2] = <K> argv[3] = <}> argv[1] = <xxx> argv[2] = <yyy> 1 argv[1] = <> argv[1] = <> argv[1] = <> argv[1] = <:a:> argv[1] = <:b:> argv[1] = <> argv[1] = <> --- NEW FILE: invert.right --- 1 1 1 0 0 1 0 1 0 1 --- NEW FILE: rsh.tests --- # test restricted shell mode -- these should all be errors # # things not tested for: # adding builtins dynamically with enable -f # importing function definitions from environment set -r cd / PATH=$PATH:/usr/local/bin SHELL=/bin/sh /bin/sh -c 'echo /bin/sh executed' . ./source.sub3 rm -f /tmp/restricted echo abc > /tmp/restricted if [ -f /tmp/restricted ]; then echo oops 1 -- output fi echo abc >> /tmp/restricted if [ -f /tmp/restricted ]; then echo oops 2 -- append fi command -p date set +r set +o restricted exec /bin/date echo $0: after exec --- NEW FILE: func.right --- a returns 5 b returns 4 c returns 3 d returns 2 in e e returned 25 x is 25 ZZ abcde defghi ZZ 5 0 AVAR AVAR foo foo AVAR 5 5 f1 f1 () { ( return 5 ); status=$?; echo $status; return $status } before: try to assign to FUNCNAME outside: FUNCNAME = before: FUNCNAME = func FUNCNAME = func2 after: FUNCNAME = func outside2: FUNCNAME = function zf is a function zf () { echo this is zf } f is a function f () { echo f-x; echo f-y } 1>&2 subshell f is a function f () { echo f-x; echo f-y } 1>&2 f2 is a function f2 () { echo f2-a; function f3 () { echo f3-a; echo f3-b } 1>&2; f3 } subshell f2 is a function f2 () { echo f2-a; function f3 () { echo f3-a; echo f3-b } 1>&2; f3 } f4 is a function f4 () { echo f4-a; function f5 () { echo f5-a; echo f5-b } 1>&2; f5 } 2>&1 subshell f4 is a function f4 () { echo f4-a; function f5 () { echo f5-a; echo f5-b } 1>&2; f5 } 2>&1 testgrp is a function testgrp () { echo testgrp-a; { echo tg-x; echo tg-y } 1>&2; echo testgrp-b } subshell testgrp is a function testgrp () { echo testgrp-a; { echo tg-x; echo tg-y } 1>&2; echo testgrp-b } funca is a function funca () { ( echo func-a ) } funcb is a function funcb () { ( echo func-b ) } funcc is a function funcc () { ( echo func-c ) 2>&1 } func-a func-b func-c expect 5 10 5 10 expect 20 20 expect 5 20 5 20 expect 5 30 5 30 expect 2 40 2 40 expect 5 20 5 20 --- NEW FILE: histexp.tests --- LC_ALL=C LANG=C trap 'rm /tmp/newhistory' 0 file=bax histchars='!^#' # make sure history comment char is set correctly history -c HISTFILE=history.list HISTCONTROL=ignoreboth HISTIGNORE='&:#*:history*:fc*' # we will end up exercising the history stifling code as a result HISTSIZE=32 shopt -s cmdhist set -o history history -p '!!' # this should result in a failed history expansion error history -p '!!:z' history HISTFILE=/tmp/newhistory history -a history -w history -s "echo line 2 for history" history history -p '!e' history -p '!!' set -H !! !e history echo a b c d e !?ch? !-2 ^2^8 !2 # we're selecting /bin/sh -c ...; we want `sh' echo !-1:0:t # we're selecting /bin/sh -c ...; we want `/bin' echo !-2:0:h # we're selecting `echo a b c d e'; we want `e' echo !?d?:5 echo a b c d e echo !-1:2-$ echo !-2:2-4 echo !-2:3* echo !!:* echo !?a?:2- echo file.c echo !!:$:r echo !-2:$:e echo !-3:$:r:q echo $file.c echo !!:$:r echo !-2:^:e echo !-3:$:r:q echo a b c d e echo !!:1-$:x echo !-2:1-$:q echo foo.c foo.o foo.html foo.h !!:s/foo/bar/ !-2:gs/foo/bar/ !!:gs/bar/x&/ !-2:g& # make sure we can use any delimiter in the substitution, not just `/' !!:gs+bar+whix+ !!:p # wow echo !?.o?:%:r:q !!:0 !?.h?:%:q !!:-$ !:-$ history # make sure single quotes inhibit history expansion echo '!!' # make sure backslashes can quote the history expansion character echo \!\! # but other expansions on the line should still be processed echo '!!' !!:* history -c unset HISTFILE # make sure that the special bash cases are not history expanded case p in [!A-Z]) echo ok 1;; esac var1='ok 2' var2=var1 echo ${!var2} # Bash-2.01[.1] fails this test -- it attempts history expansion after the # history_expansion_char echo ok 3 # !1200 --- NEW FILE: arith.right --- 163 166 4 16 8 2 4 2 2 1 0 0 0 1 1 2 -3 -2 1 0 2 131072 29 33 49 1 1 0 0 1 1 1 2 3 1 58 2 60 1 256 16 62 4 29 5 -4 4 1 32 32 1 1 32 20 1,i+=2 30 1,j+=2 20 1,i+=2 30 1,j+=2 ./arith.tests: line 108: 1 ? 20 : x+=2: attempted assignment to non-variable (error token is "+=2") 20 6 6,5,3 263 255 255 127 36 40 10 10 10 10 10 10 36 36 62 63 ./arith.tests: line 143: 3425#56: illegal arithmetic base (error token is "3425#56") 0 ./arith.tests: line 149: 7 = 43 : attempted assignment to non-variable (error token is "= 43 ") ./arith.tests: line 150: 2#44: value too great for base (error token is "2#44") ./arith.tests: line 151: 44 / 0 : division by 0 (error token is " ") ./arith.tests: line 152: let: jv += $iv: syntax error: operand expected (error token is "$iv") ./arith.tests: line 153: jv += $iv : syntax error: operand expected (error token is "$iv ") ./arith.tests: line 154: let: rv = 7 + (43 * 6: missing `)' (error token is "6") ./arith.tests: line 158: 0#4: bad number (error token is "0#4") ./arith.tests: line 159: 2#110#11: bad number (error token is "2#110#11") abc def ghi ok 6 1 0 ./arith.tests: line 177: 4 + : syntax error: operand expected (error token is " ") 16 ./arith.tests: line 182: 4 ? : 3 + 5 : expression expected (error token is ": 3 + 5 ") ./arith.tests: line 183: 1 ? 20 : `:' expected for conditional expression (error token is " ") ./arith.tests: line 184: 4 ? 20 : : expression expected (error token is " ") 9 ./arith.tests: line 190: 0 && B=42 : attempted assignment to non-variable (error token is "=42 ") 9 ./arith.tests: line 193: 1 || B=88 : attempted assignment to non-variable (error token is "=88 ") 9 0 9 0 9 1 9 7 7 4 32767 32768 131072 2147483647 1 4 4 5 5 4 3 3 4 4 7 ./arith.tests: line 241: 7-- : syntax error: operand expected (error token is " ") ./arith.tests: line 243: --x=7 : attempted assignment to non-variable (error token is "=7 ") ./arith.tests: line 244: ++x=7 : attempted assignment to non-variable (error token is "=7 ") ./arith.tests: line 246: x++=7 : attempted assignment to non-variable (error token is "=7 ") ./arith.tests: line 247: x--=7 : attempted assignment to non-variable (error token is "=7 ") 4 7 -7 7 7 8 12 ./arith.tests: line 265: ((: x=9 y=41 : syntax error in expression (error token is "y=41 ") ./arith.tests: line 269: a b: syntax error in expression (error token is "b") ./arith.tests: line 270: ((: a b: syntax error in expression (error token is "b") 42 42 42 42 42 42 --- NEW FILE: run-shopt --- ${THIS_SH} ./shopt.tests > /tmp/xx 2>&1 diff /tmp/xx shopt.right && rm -f /tmp/xx --- NEW FILE: input.right --- before calling input-line.sub line read by ./input-line.sub was `this line for input-line.sub' finished with input-line.sub --- NEW FILE: jobs3.sub --- #! /bin/bash NJOB=8 i=0 while [ $i -lt $NJOB ] do /bin/sh -c "sleep 4; exit 0" & rv=$? pid=$! eval bg_pid_$i=$pid # echo $$: Job $i: pid is $pid rv=$rv i=$((i + 1)) done i=0 while [ $i -lt $NJOB ] do eval wpid=\$bg_pid_$i echo Waiting for job $i #'('pid $wpid')' wait $wpid rv=$? echo job $i returns $rv i=$((i + 1)) done --- NEW FILE: redir5.sub --- # tests of ksh93-like dup-and-close redirection operators exec 9<$0 f() { exec 5<$0 exec 0<&5- while read line; do echo "$line" done } f typeset -f f # make sure it was closed read -u 5 foo echo after read exec 5<&0 exec <&- read abcde exec 0<&9- read line echo $line --- NEW FILE: run-set-e --- ${THIS_SH} ./set-e-test > /tmp/xx diff /tmp/xx set-e.right && rm -f /tmp/xx --- NEW FILE: braces-tests --- echo ff{c,b,a} echo f{d,e,f}g echo {l,n,m}xyz echo {abc\,def} echo {abc} echo \{a,b,c,d,e} echo {x,y,\{a,b,c}} echo {x\,y,\{abc\},trie} echo /usr/{ucb/{ex,edit},lib/{ex,how_ex}} echo XXXX\{`echo a b c | tr ' ' ','`\} eval echo XXXX\{`echo a b c | tr ' ' ','`\} echo {} echo { } echo } echo { echo abcd{efgh echo foo {1,2} bar echo `zecho foo {1,2} bar` echo $(zecho foo {1,2} bar) --- NEW FILE: source3.sub --- echo "$@" --- NEW FILE: glob-test --- LC_COLLATE=C # # test the shell globbing # expect() { echo expect "$@" } # First, a test that bash-2.01.1 fails ${THIS_SH} ./glob1.sub MYDIR=$PWD # save where we are TESTDIR=/tmp/glob-test mkdir $TESTDIR builtin cd $TESTDIR || { echo $0: cannot cd to $TESTDIR >&2 ; exit 1; } rm -rf * touch a b c d abc abd abe bb bcd ca cb dd de Beware mkdir bdir # see if `regular' globbing works right expect '<a> <abc> <abd> <abe> <X*>' recho a* X* expect '<a> <abc> <abd> <abe>' recho \a* # see if null glob expansion works shopt -s nullglob expect '<a> <abc> <abd> <abe>' recho a* X* shopt -u nullglob # see if the code that expands directories only works expect '<bdir/>' recho b*/ # Test quoted and unquoted globbing characters expect '<*>' recho \* expect '<a*>' recho 'a*' expect '<a*>' recho a\* expect '<c> <ca> <cb> <a*> <*q*>' recho c* a\* *q* expect '<**>' recho "*"* expect '<**>' recho \** expect '<\.\./*/>' recho "\.\./*/" expect '<s/\..*//>' recho 's/\..*//' # Pattern from Larry Wall's Configure that caused bash to blow up expect '</^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/>' recho "/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*"'$'"/\1/" # Make sure character classes work properly expect '<abc> <abd> <abe> <bb> <cb>' recho [a-c]b* expect '<abd> <abe> <bb> <bcd> <bdir> <ca> <cb> <dd> <de>' recho [a-y]*[^c] expect '<abd> <abe>' recho a*[^c] touch a-b aXb expect '<a-b> <aXb>' recho a[X-]b touch .x .y expect '<Beware> <d> <dd> <de>' recho [^a-c]* # Make sure that filenames with embedded globbing characters are handled # properly mkdir a\*b > a\*b/ooo expect '<a*b/ooo>' recho a\*b/* expect '<a*b/ooo>' recho a\*?/* expect '<no match>' cmd='echo !7' case "$cmd" in *\\!*) echo match ;; *) echo no match ;; esac expect '<not there>' file='r.*' case $file in *.\*) echo not there ;; *) echo there ;; esac # examples from the Posix.2 spec (d11.2, p. 243) expect '<abc>' recho a[b]c expect '<abc>' recho a["b"]c expect '<abc>' recho a[\b]c expect '<abc>' recho a?c expect '<match 1>' case abc in a"b"c) echo 'match 1' ;; *) echo 'BAD match 1' ;; esac expect '<match 2>' case abc in a*c) echo 'match 2' ;; *) echo 'BAD match 2' ;; esac expect '<ok 1>' case abc in "a?c") echo 'bad 1' ;; *) echo 'ok 1' ;; esac expect '<ok 2>' case abc in a\*c) echo 'bad 2' ;; *) echo 'ok 2' ;; esac expect '<ok 3>' case abc in a\[b]c) echo 'bad 3' ;; *) echo 'ok 3' ;; esac expect '<ok 4>' case "$nosuchvar" in "") echo 'ok 4' ;; *) echo 'bad 4' ;; esac # This is very odd, but sh and ksh seem to agree expect '<ok 5>' case abc in a["\b"]c) echo 'ok 5' ;; *) echo 'bad 5' ;; esac mkdir man mkdir man/man1 touch man/man1/bash.1 expect '<man/man1/bash.1>' recho */man*/bash.* expect '<man/man1/bash.1>' recho $(echo */man*/bash.*) expect '<man/man1/bash.1>' recho "$(echo */man*/bash.*)" # tests with multiple `*'s case abc in a***c) echo ok 1;; esac case abc in a*****?c) echo ok 2;; esac case abc in ?*****??) echo ok 3;; esac case abc in *****??) echo ok 4;; esac case abc in *****??c) echo ok 5;; esac case abc in ?*****?c) echo ok 6;; esac case abc in ?***?****c) echo ok 7;; esac case abc in ?***?****?) echo ok 8;; esac case abc in ?***?****) echo ok 9;; esac case abc in *******c) echo ok 10;; esac case abc in *******?) echo ok 11;; esac case abcdecdhjk in a*cd**?**??k) echo ok 20;; esac case abcdecdhjk in a**?**cd**?**??k) echo ok 21;; esac case abcdecdhjk in a**?**cd**?**??k***) echo ok 22;; esac case abcdecdhjk in a**?**cd**?**??***k) echo ok 23;; esac case abcdecdhjk in a**?**cd**?**??***k**) echo ok 24;; esac ca... [truncated message content] |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:36
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/tilde/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/tilde/doc Added Files: Makefile tilde.texi Log Message: Pristine source --- NEW FILE: tilde.texi --- --- NEW FILE: Makefile --- clean distclean mostlyclean maintainer-clean: rm -f tilde.?? all: cp tilde.texi tilde.info |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:36
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/termcap In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/termcap Added Files: Makefile.in ltcap.h termcap.c termcap.h tparam.c version.c Log Message: Pristine source --- NEW FILE: tparam.c --- /* Merge parameters into a termcap entry string. Copyright (C) 1985, 87, 93, 95 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* Emacs config.h may rename various library functions such as malloc. */ #ifdef HAVE_CONFIG_H #include <config.h> #ifdef HAVE_STDLIB_H # include <stdlib.h> #else extern char *getenv (); extern char *malloc (); extern char *realloc (); #endif #else /* not HAVE_CONFIG_H */ #if defined(HAVE_STRING_H) || defined(STDC_HEADERS) #define bcopy(s, d, n) memcpy ((d), (s), (n)) #endif #ifdef STDC_HEADERS #include <stdlib.h> #include <string.h> #else char *malloc (); char *realloc (); #endif #endif /* not HAVE_CONFIG_H */ #include "ltcap.h" #ifndef NULL #define NULL (char *) 0 #endif #ifndef emacs static void memory_out () { write (2, "virtual memory exhausted\n", 25); exit (1); } static char * xmalloc (size) unsigned size; { register char *tem = malloc (size); if (!tem) memory_out (); return tem; } static char * xrealloc (ptr, size) char *ptr; unsigned size; { register char *tem = realloc (ptr, size); if (!tem) memory_out (); return tem; } #endif /* not emacs */ /* Assuming STRING is the value of a termcap string entry containing `%' constructs to expand parameters, merge in parameter values and store result in block OUTSTRING points to. LEN is the length of OUTSTRING. If more space is needed, a block is allocated with `malloc'. The value returned is the address of the resulting string. This may be OUTSTRING or may be the address of a block got with `malloc'. In the latter case, the caller must free the block. The fourth and following args to tparam serve as the parameter values. */ static char *tparam1 (); /* VARARGS 2 */ char * tparam (string, outstring, len, arg0, arg1, arg2, arg3) char *string; char *outstring; int len; int arg0, arg1, arg2, arg3; { int arg[4]; arg[0] = arg0; arg[1] = arg1; arg[2] = arg2; arg[3] = arg3; return tparam1 (string, outstring, len, NULL, NULL, arg); } __private_extern__ char *BC; __private_extern__ char *UP; static char tgoto_buf[50]; __private_extern__ char * tgoto (cm, hpos, vpos) char *cm; int hpos, vpos; { int args[2]; if (!cm) return NULL; args[0] = vpos; args[1] = hpos; return tparam1 (cm, tgoto_buf, 50, UP, BC, args); } static char * tparam1 (string, outstring, len, up, left, argp) char *string; char *outstring; int len; char *up, *left; register int *argp; { register int c; register char *p = string; register char *op = outstring; char *outend; int outlen = 0; register int tem; int *old_argp = argp; int doleft = 0; int doup = 0; outend = outstring + len; while (1) { /* If the buffer might be too short, make it bigger. */ if (op + 5 >= outend) { register char *new; if (outlen == 0) { outlen = len + 40; new = (char *) xmalloc (outlen); outend += 40; bcopy (outstring, new, op - outstring); } else { outend += outlen; outlen *= 2; new = (char *) xrealloc (outstring, outlen); } op += new - outstring; outend += new - outstring; outstring = new; } c = *p++; if (!c) break; if (c == '%') { c = *p++; tem = *argp; switch (c) { case 'd': /* %d means output in decimal. */ if (tem < 10) goto onedigit; if (tem < 100) goto twodigit; case '3': /* %3 means output in decimal, 3 digits. */ if (tem > 999) { *op++ = tem / 1000 + '0'; tem %= 1000; } *op++ = tem / 100 + '0'; case '2': /* %2 means output in decimal, 2 digits. */ twodigit: tem %= 100; *op++ = tem / 10 + '0'; onedigit: *op++ = tem % 10 + '0'; argp++; break; case 'C': /* For c-100: print quotient of value by 96, if nonzero, then do like %+. */ if (tem >= 96) { *op++ = tem / 96; tem %= 96; } case '+': /* %+x means add character code of char x. */ tem += *p++; case '.': /* %. means output as character. */ if (left) { /* If want to forbid output of 0 and \n and \t, and this is one of them, increment it. */ while (tem == 0 || tem == '\n' || tem == '\t') { tem++; if (argp == old_argp) doup++, outend -= strlen (up); else doleft++, outend -= strlen (left); } } *op++ = tem ? tem : 0200; case 'f': /* %f means discard next arg. */ argp++; break; case 'b': /* %b means back up one arg (and re-use it). */ argp--; break; case 'r': /* %r means interchange following two args. */ argp[0] = argp[1]; argp[1] = tem; old_argp++; break; case '>': /* %>xy means if arg is > char code of x, */ if (argp[0] > *p++) /* then add char code of y to the arg, */ argp[0] += *p; /* and in any case don't output. */ p++; /* Leave the arg to be output later. */ break; case 'a': /* %a means arithmetic. */ /* Next character says what operation. Add or subtract either a constant or some other arg. */ /* First following character is + to add or - to subtract or = to assign. */ /* Next following char is 'p' and an arg spec (0100 plus position of that arg relative to this one) or 'c' and a constant stored in a character. */ tem = p[2] & 0177; if (p[1] == 'p') tem = argp[tem - 0100]; if (p[0] == '-') argp[0] -= tem; else if (p[0] == '+') argp[0] += tem; else if (p[0] == '*') argp[0] *= tem; else if (p[0] == '/') argp[0] /= tem; else argp[0] = tem; p += 3; break; case 'i': /* %i means add one to arg, */ argp[0] ++; /* and leave it to be output later. */ argp[1] ++; /* Increment the following arg, too! */ break; case '%': /* %% means output %; no arg. */ goto ordinary; case 'n': /* %n means xor each of next two args with 140. */ argp[0] ^= 0140; argp[1] ^= 0140; break; case 'm': /* %m means xor each of next two args with 177. */ argp[0] ^= 0177; argp[1] ^= 0177; break; case 'B': /* %B means express arg as BCD char code. */ argp[0] += 6 * (tem / 10); break; case 'D': /* %D means weird Delta Data transformation. */ argp[0] -= 2 * (tem % 16); break; } } else /* Ordinary character in the argument string. */ ordinary: *op++ = c; } *op = 0; while (doup-- > 0) strcat (op, up); while (doleft-- > 0) strcat (op, left); return outstring; } #ifdef DEBUG main (argc, argv) int argc; char **argv; { char buf[50]; int args[3]; args[0] = atoi (argv[2]); args[1] = atoi (argv[3]); args[2] = atoi (argv[4]); tparam1 (argv[1], buf, "LEFT", "UP", args); printf ("%s\n", buf); return 0; } #endif /* DEBUG */ --- NEW FILE: termcap.h --- /* Declarations for termcap library. Copyright (C) 1991, 1992, 1995 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #ifndef _TERMCAP_H #define _TERMCAP_H 1 #if __STDC__ extern int tgetent (char *buffer, const char *termtype); extern int tgetnum (const char *name); extern int tgetflag (const char *name); extern char *tgetstr (const char *name, char **area); extern char PC; extern short ospeed; extern void tputs (const char *string, int nlines, int (*outfun) (int)); extern char *tparam (const char *ctlstring, char *buffer, int size, ...); extern char *UP; extern char *BC; extern char *tgoto (const char *cstring, int hpos, int vpos); #else /* not __STDC__ */ extern int tgetent (); extern int tgetnum (); extern int tgetflag (); extern char *tgetstr (); extern char PC; extern short ospeed; extern void tputs (); extern char *tparam (); extern char *UP; extern char *BC; extern char *tgoto (); #endif /* not __STDC__ */ #endif /* not _TERMCAP_H */ --- NEW FILE: Makefile.in --- ## -*- text -*- #################################################### # # # Makefile for termcap replacement libbrary. # # # #################################################################### # Copyright (C) 1996 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. srcdir = @srcdir@ VPATH = .:@srcdir@ topdir = @top_srcdir@ BUILD_DIR = @BUILD_DIR@ libdir = @libdir@ INSTALL = @INSTALL@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_DATA = @INSTALL_DATA@ CC = @CC@ RANLIB = @RANLIB@ AR = @AR@ ARFLAGS = @ARFLAGS@ RM = rm -f CP = cp MV = mv SHELL = @MAKE_SHELL@ CFLAGS = @CFLAGS@ CPPFLAGS = @CPPFLAGS@ LDFLAGS = @LDFLAGS@ DEFS = @DEFS@ INCLUDES = -I. -I../.. -I$(topdir) -I$(topdir)/lib -I$(srcdir) CCFLAGS = $(CFLAGS) $(DEFS) $(CPPFLAGS) ${INCLUDES} # Here is a rule for making .o files from .c files that doesn't force # the type of the machine (like -sun3) into the flags. .c.o: $(CC) -c $(CCFLAGS) $< SOURCES = termcap.c tparam.c OBJECTS = termcap.o tparam.o DOCUMENTATION = termcap.texinfo THINGS_TO_TAR = $(SOURCES) $(DOCUMENTATION) ########################################################################## all: libtermcap.a libtermcap.a: $(OBJECTS) $(RM) -f $@ $(AR) $(ARFLAGS) $@ $(OBJECTS) -test -n "$(RANLIB)" && $(RANLIB) $@ install: clean: $(RM) *.o *.a *.log *.cp *.tp *.vr *.fn *.aux *.pg *.toc mostlyclean: clean distclean maintainer-clean: clean $(RM) Makefile $(DESTDIR)$(libdir)/libtermcap.a: libtermcap.a ${INSTALL_DATA} -c -m 644 libtermcap.a $@ -test -n "$(RANLIB)" && $(RANLIB) -t $@ termcap.o: $(BUILD_DIR)/config.h tparam.o: $(BUILD_DIR)/config.h version.o: $(BUILD_DIR)/config.h --- NEW FILE: version.c --- /* Copyright (C) 1985-2002 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* Make the library identifiable with the RCS ident command. */ static char *termcap_version_string = "\n$Version: GNU termcap 1.3 $\n"; --- NEW FILE: ltcap.h --- /* Local declarations for termcap library. Copyright (C) 1999 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #ifndef _LTCAP_H_ #define _LTCAP_H_ 1 #if !defined (__APPLE__) # define __private_extern__ #endif #ifndef MAX_TGETENT_BUFSIZ # define MAX_TGETENT_BUFSIZ 2048 #endif #endif /* _LTCAP_H_ */ --- NEW FILE: termcap.c --- /* Work-alike for termcap, plus extra features. Copyright (C) 1985, 86, 93, 94, 95 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* Emacs config.h may rename various library functions such as malloc. */ #ifdef HAVE_CONFIG_H #include <config.h> /* Get the O_* definitions for open et al. */ #ifndef _MINIX #include <sys/file.h> #endif #include <fcntl.h> #ifdef HAVE_STDLIB_H # include <stdlib.h> #else extern char *getenv (); extern char *malloc (); extern char *realloc (); #endif #else /* not HAVE_CONFIG_H */ #ifdef STDC_HEADERS #include <stdlib.h> #include <string.h> #else char *getenv (); char *malloc (); char *realloc (); #endif /* Do this after the include, in case string.h prototypes bcopy. */ #if (defined(HAVE_STRING_H) || defined(STDC_HEADERS)) && !defined(bcopy) #define bcopy(s, d, n) memcpy ((d), (s), (n)) #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef _POSIX_VERSION #include <fcntl.h> #endif #endif /* not HAVE_CONFIG_H */ #ifndef NULL #define NULL (char *) 0 #endif #ifndef O_RDONLY #define O_RDONLY 0 #endif /* BUFSIZE is the initial size allocated for the buffer for reading the termcap file. It is not a limit. Make it large normally for speed. Make it variable when debugging, so can exercise increasing the space dynamically. */ #ifndef BUFSIZE #ifdef DEBUG #define BUFSIZE bufsize int bufsize = 128; #else #define BUFSIZE 2048 #endif #endif #include "ltcap.h" #ifndef TERMCAP_FILE #define TERMCAP_FILE "/etc/termcap" #endif #ifndef emacs static void memory_out () { write (2, "virtual memory exhausted\n", 25); exit (1); } static char * xmalloc (size) unsigned size; { register char *tem = malloc (size); if (!tem) memory_out (); return tem; } static char * xrealloc (ptr, size) char *ptr; unsigned size; { register char *tem = realloc (ptr, size); if (!tem) memory_out (); return tem; } #endif /* not emacs */ /* Looking up capabilities in the entry already found. */ /* The pointer to the data made by tgetent is left here for tgetnum, tgetflag and tgetstr to find. */ static char *term_entry; static char *tgetst1 (); /* Search entry BP for capability CAP. Return a pointer to the capability (in BP) if found, 0 if not found. */ static char * find_capability (bp, cap) register char *bp, *cap; { for (; *bp; bp++) if (bp[0] == ':' && bp[1] == cap[0] && bp[2] == cap[1]) return &bp[4]; return NULL; } __private_extern__ int tgetnum (cap) char *cap; { register char *ptr = find_capability (term_entry, cap); if (!ptr || ptr[-1] != '#') return -1; return atoi (ptr); } __private_extern__ int tgetflag (cap) char *cap; { register char *ptr = find_capability (term_entry, cap); return ptr && ptr[-1] == ':'; } /* Look up a string-valued capability CAP. If AREA is non-null, it points to a pointer to a block in which to store the string. That pointer is advanced over the space used. If AREA is null, space is allocated with `malloc'. */ __private_extern__ char * tgetstr (cap, area) char *cap; char **area; { register char *ptr = find_capability (term_entry, cap); if (!ptr || (ptr[-1] != '=' && ptr[-1] != '~')) return NULL; return tgetst1 (ptr, area); } /* Table, indexed by a character in range 0100 to 0140 with 0100 subtracted, gives meaning of character following \, or a space if no special meaning. Eight characters per line within the string. */ static char esctab[] = " \007\010 \033\014 \ \012 \ \015 \011 \013 \ "; /* PTR points to a string value inside a termcap entry. Copy that value, processing \ and ^ abbreviations, into the block that *AREA points to, or to newly allocated storage if AREA is NULL. Return the address to which we copied the value, or NULL if PTR is NULL. */ static char * tgetst1 (ptr, area) char *ptr; char **area; { register char *p, *r; register int c; register int size; char *ret; register int c1; if (!ptr) return NULL; /* `ret' gets address of where to store the string. */ if (!area) { /* Compute size of block needed (may overestimate). */ p = ptr; while ((c = *p++) && c != ':' && c != '\n') ; ret = (char *) xmalloc (p - ptr + 1); } else ret = *area; /* Copy the string value, stopping at null or colon. Also process ^ and \ abbreviations. */ p = ptr; r = ret; while ((c = *p++) && c != ':' && c != '\n') { if (c == '^') { c = *p++; if (c == '?') c = 0177; else c &= 037; } else if (c == '\\') { c = *p++; if (c >= '0' && c <= '7') { c -= '0'; size = 0; while (++size < 3 && (c1 = *p) >= '0' && c1 <= '7') { c *= 8; c += c1 - '0'; p++; } } else if (c >= 0100 && c < 0200) { c1 = esctab[(c & ~040) - 0100]; if (c1 != ' ') c = c1; } } *r++ = c; } *r = '\0'; /* Update *AREA. */ if (area) *area = r + 1; return ret; } /* Outputting a string with padding. */ short ospeed; /* If OSPEED is 0, we use this as the actual baud rate. */ int tputs_baud_rate; __private_extern__ char PC = '\0'; /* Actual baud rate if positive; - baud rate / 100 if negative. */ static int speeds[] = { #ifdef VMS 0, 50, 75, 110, 134, 150, -3, -6, -12, -18, -20, -24, -36, -48, -72, -96, -192 #else /* not VMS */ 0, 50, 75, 110, 135, 150, -2, -3, -6, -12, -18, -24, -48, -96, -192, -288, -384, -576, -1152 #endif /* not VMS */ }; __private_extern__ void tputs (str, nlines, outfun) register char *str; int nlines; register int (*outfun) (); { register int padcount = 0; register int speed; #ifdef emacs extern baud_rate; speed = baud_rate; /* For quite high speeds, convert to the smaller units to avoid overflow. */ if (speed > 10000) speed = - speed / 100; #else if (ospeed == 0) speed = tputs_baud_rate; else if (ospeed > 0 && ospeed < (sizeof speeds / sizeof speeds[0])) speed = speeds[ospeed]; else speed = 0; #endif if (!str) return; while (*str >= '0' && *str <= '9') { padcount += *str++ - '0'; padcount *= 10; } if (*str == '.') { str++; padcount += *str++ - '0'; } if (*str == '*') { str++; padcount *= nlines; } while (*str) (*outfun) (*str++); /* PADCOUNT is now in units of tenths of msec. SPEED is measured in characters per 10 seconds or in characters per .1 seconds (if negative). We use the smaller units for larger speeds to avoid overflow. */ padcount *= speed; padcount += 500; padcount /= 1000; if (speed < 0) padcount = -padcount; else { padcount += 50; padcount /= 100; } while (padcount-- > 0) (*outfun) (PC); } /* Finding the termcap entry in the termcap data base. */ struct buffer { char *beg; int size; char *ptr; int ateof; int full; }; /* Forward declarations of static functions. */ static int scan_file (); static char *gobble_line (); static int compare_contin (); static int name_match (); #ifdef VMS #include <rmsdef.h> #include <fab.h> #include <nam.h> static int valid_filename_p (fn) char *fn; { struct FAB fab = cc$rms_fab; struct NAM nam = cc$rms_nam; char esa[NAM$C_MAXRSS]; fab.fab$l_fna = fn; fab.fab$b_fns = strlen(fn); fab.fab$l_nam = &nam; fab.fab$l_fop = FAB$M_NAM; nam.nam$l_esa = esa; nam.nam$b_ess = sizeof esa; return SYS$PARSE(&fab, 0, 0) == RMS$_NORMAL; } #else /* !VMS */ #ifdef MSDOS /* MW, May 1993 */ static int valid_filename_p (fn) char *fn; { return *fn == '\\' || *fn == '/' || (*fn >= 'A' && *fn <= 'z' && fn[1] == ':'); } #else #define valid_filename_p(fn) (*(fn) == '/') #endif #endif /* !VMS */ /* Find the termcap entry data for terminal type NAME and store it in the block that BP points to. Record its address for future use. If BP is null, space is dynamically allocated. Return -1 if there is some difficulty accessing the data base of terminal types, 0 if the data base is accessible but the type NAME is not defined in it, and some other value otherwise. */ __private_extern__ int tgetent (bp, name) char *bp, *name; { register char *termcap_name; register int fd; struct buffer buf; register char *bp1; char *bp2; char *term; int malloc_size = 0; register int c; char *tcenv; /* TERMCAP value, if it contains :tc=. */ char *indirect = NULL; /* Terminal type in :tc= in TERMCAP value. */ int filep; #ifdef INTERNAL_TERMINAL /* For the internal terminal we don't want to read any termcap file, so fake it. */ if (!strcmp (name, "internal")) { term = INTERNAL_TERMINAL; if (!bp) { malloc_size = 1 + strlen (term); bp = (char *) xmalloc (malloc_size); } strcpy (bp, term); goto ret; } #endif /* INTERNAL_TERMINAL */ /* For compatibility with programs like `less' that want to put data in the termcap buffer themselves as a fallback. */ if (bp) term_entry = bp; termcap_name = getenv ("TERMCAP"); if (termcap_name && *termcap_name == '\0') termcap_name = NULL; #if 0 #if defined (MSDOS) && !defined (TEST) if (termcap_name && (*termcap_name == '\\' || *termcap_name == '/' || termcap_name[1] == ':')) dostounix_filename(termcap_name); #endif #endif filep = termcap_name && valid_filename_p (termcap_name); /* If termcap_name is non-null and starts with / (in the un*x case, that is), it is a file name to use instead of /etc/termcap. If it is non-null and does not start with /, it is the entry itself, but only if the name the caller requested matches the TERM variable. */ if (termcap_name && !filep && !strcmp (name, getenv ("TERM"))) { indirect = tgetst1 (find_capability (termcap_name, "tc"), (char **) 0); if (!indirect) { if (!bp) bp = termcap_name; else strcpy (bp, termcap_name); goto ret; } else { /* It has tc=. Need to read /etc/termcap. */ tcenv = termcap_name; termcap_name = NULL; } } if (!termcap_name || !filep) termcap_name = TERMCAP_FILE; /* Here we know we must search a file and termcap_name has its name. */ #ifdef MSDOS fd = open (termcap_name, O_RDONLY|O_TEXT, 0); #else fd = open (termcap_name, O_RDONLY, 0); #endif if (fd < 0) return -1; buf.size = BUFSIZE; /* Add 1 to size to ensure room for terminating null. */ buf.beg = (char *) xmalloc (buf.size + 1); term = indirect ? indirect : name; if (!bp) { malloc_size = indirect ? strlen (tcenv) + 1 : buf.size; bp = (char *) xmalloc (malloc_size); } bp1 = bp; if (indirect) /* Copy the data from the environment variable. */ { strcpy (bp, tcenv); bp1 += strlen (tcenv); } while (term) { /* Scan the file, reading it via buf, till find start of main entry. */ if (scan_file (term, fd, &buf) == 0) { close (fd); free (buf.beg); if (malloc_size) free (bp); return 0; } /* Free old `term' if appropriate. */ if (term != name) free (term); /* If BP is malloc'd by us, make sure it is big enough. */ if (malloc_size) { malloc_size = bp1 - bp + buf.size; termcap_name = (char *) xrealloc (bp, malloc_size); bp1 += termcap_name - bp; bp = termcap_name; } bp2 = bp1; /* Copy the line of the entry from buf into bp. */ termcap_name = buf.ptr; while ((*bp1++ = c = *termcap_name++) && c != '\n') /* Drop out any \ newline sequence. */ if (c == '\\' && *termcap_name == '\n') { bp1--; termcap_name++; } *bp1 = '\0'; /* Does this entry refer to another terminal type's entry? If something is found, copy it into heap and null-terminate it. */ term = tgetst1 (find_capability (bp2, "tc"), (char **) 0); } close (fd); free (buf.beg); if (malloc_size) bp = (char *) xrealloc (bp, bp1 - bp + 1); ret: term_entry = bp; return 1; } /* Given file open on FD and buffer BUFP, scan the file from the beginning until a line is found that starts the entry for terminal type STR. Return 1 if successful, with that line in BUFP, or 0 if no entry is found in the file. */ static int scan_file (str, fd, bufp) char *str; int fd; register struct buffer *bufp; { register char *end; bufp->ptr = bufp->beg; bufp->full = 0; bufp->ateof = 0; *bufp->ptr = '\0'; lseek (fd, 0L, 0); while (!bufp->ateof) { /* Read a line into the buffer. */ end = NULL; do { /* if it is continued, append another line to it, until a non-continued line ends. */ end = gobble_line (fd, bufp, end); } while (!bufp->ateof && end[-2] == '\\'); if (*bufp->ptr != '#' && name_match (bufp->ptr, str)) return 1; /* Discard the line just processed. */ bufp->ptr = end; } return 0; } /* Return nonzero if NAME is one of the names specified by termcap entry LINE. */ static int name_match (line, name) char *line, *name; { register char *tem; if (!compare_contin (line, name)) return 1; /* This line starts an entry. Is it the right one? */ for (tem = line; *tem && *tem != '\n' && *tem != ':'; tem++) if (*tem == '|' && !compare_contin (tem + 1, name)) return 1; return 0; } static int compare_contin (str1, str2) register char *str1, *str2; { register int c1, c2; while (1) { c1 = *str1++; c2 = *str2++; while (c1 == '\\' && *str1 == '\n') { str1++; while ((c1 = *str1++) == ' ' || c1 == '\t'); } if (c2 == '\0') { /* End of type being looked up. */ if (c1 == '|' || c1 == ':') /* If end of name in data base, we win. */ return 0; else return 1; } else if (c1 != c2) return 1; } } /* Make sure that the buffer <- BUFP contains a full line of the file open on FD, starting at the place BUFP->ptr points to. Can read more of the file, discard stuff before BUFP->ptr, or make the buffer bigger. Return the pointer to after the newline ending the line, or to the end of the file, if there is no newline to end it. Can also merge on continuation lines. If APPEND_END is non-null, it points past the newline of a line that is continued; we add another line onto it and regard the whole thing as one line. The caller decides when a line is continued. */ static char * gobble_line (fd, bufp, append_end) int fd; register struct buffer *bufp; char *append_end; { register char *end; register int nread; register char *buf = bufp->beg; register char *tem; if (!append_end) append_end = bufp->ptr; while (1) { end = append_end; while (*end && *end != '\n') end++; if (*end) break; if (bufp->ateof) return buf + bufp->full; if (bufp->ptr == buf) { if (bufp->full == bufp->size) { bufp->size *= 2; /* Add 1 to size to ensure room for terminating null. */ tem = (char *) xrealloc (buf, bufp->size + 1); bufp->ptr = (bufp->ptr - buf) + tem; append_end = (append_end - buf) + tem; bufp->beg = buf = tem; } } else { append_end -= bufp->ptr - buf; bcopy (bufp->ptr, buf, bufp->full -= bufp->ptr - buf); bufp->ptr = buf; } if (!(nread = read (fd, buf + bufp->full, bufp->size - bufp->full))) bufp->ateof = 1; bufp->full += nread; buf[bufp->full] = '\0'; } return end + 1; } #ifdef TEST #ifdef NULL #undef NULL #endif #include <stdio.h> main (argc, argv) int argc; char **argv; { char *term; char *buf; term = argv[1]; printf ("TERM: %s\n", term); buf = (char *) tgetent (0, term); if ((int) buf <= 0) { printf ("No entry.\n"); return 0; } printf ("Entry: %s\n", buf); tprint ("cm"); tprint ("AL"); printf ("co: %d\n", tgetnum ("co")); printf ("am: %d\n", tgetflag ("am")); } tprint (cap) char *cap; { char *x = tgetstr (cap, 0); register char *y; printf ("%s: ", cap); if (x) { for (y = x; *y; y++) if (*y <= ' ' || *y == 0177) printf ("\\%0o", *y); else putchar (*y); free (x); } else printf ("none"); putchar ('\n'); } #endif /* TEST */ |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:36
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/glob In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/glob Added Files: Makefile.in collsyms.h glob.c glob.h glob_loop.c ndir.h sm_loop.c smatch.c strmatch.c strmatch.h xmbsrtowcs.c Log Message: Pristine source --- NEW FILE: sm_loop.c --- /* Copyright (C) 1991-2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ static int FCT __P((CHAR *, CHAR *, int)); static int GMATCH __P((CHAR *, CHAR *, CHAR *, CHAR *, int)); static CHAR *PARSE_COLLSYM __P((CHAR *, INT *)); static CHAR *BRACKMATCH __P((CHAR *, U_CHAR, int)); static int EXTMATCH __P((INT, CHAR *, CHAR *, CHAR *, CHAR *, int)); static CHAR *PATSCAN __P((CHAR *, CHAR *, INT)); static int FCT (pattern, string, flags) CHAR *pattern; CHAR *string; int flags; { CHAR *se, *pe; if (string == 0 || pattern == 0) return FNM_NOMATCH; se = string + STRLEN ((XCHAR *)string); pe = pattern + STRLEN ((XCHAR *)pattern); return (GMATCH (string, se, pattern, pe, flags)); } /* Match STRING against the filename pattern PATTERN, returning zero if it matches, FNM_NOMATCH if not. */ static int GMATCH (string, se, pattern, pe, flags) CHAR *string, *se; CHAR *pattern, *pe; int flags; { CHAR *p, *n; /* pattern, string */ INT c; /* current pattern character - XXX U_CHAR? */ INT sc; /* current string character - XXX U_CHAR? */ p = pattern; n = string; if (string == 0 || pattern == 0) return FNM_NOMATCH; #if DEBUG_MATCHING fprintf(stderr, "gmatch: string = %s; se = %s\n", string, se); fprintf(stderr, "gmatch: pattern = %s; pe = %s\n", pattern, pe); #endif while (p < pe) { c = *p++; c = FOLD (c); sc = n < se ? *n : '\0'; #ifdef EXTENDED_GLOB /* EXTMATCH () will handle recursively calling GMATCH, so we can just return what EXTMATCH() returns. */ if ((flags & FNM_EXTMATCH) && *p == L('(') && (c == L('+') || c == L('*') || c == L('?') || c == L('@') || c == L('!'))) /* ) */ { int lflags; /* If we're not matching the start of the string, we're not concerned about the special cases for matching `.' */ lflags = (n == string) ? flags : (flags & ~FNM_PERIOD); return (EXTMATCH (c, n, se, p, pe, lflags)); } #endif /* EXTENDED_GLOB */ switch (c) { case L('?'): /* Match single character */ if (sc == '\0') return FNM_NOMATCH; else if ((flags & FNM_PATHNAME) && sc == L('/')) /* If we are matching a pathname, `?' can never match a `/'. */ return FNM_NOMATCH; else if ((flags & FNM_PERIOD) && sc == L('.') && (n == string || ((flags & FNM_PATHNAME) && n[-1] == L('/')))) /* `?' cannot match a `.' if it is the first character of the string or if it is the first character following a slash and we are matching a pathname. */ return FNM_NOMATCH; break; case L('\\'): /* backslash escape removes special meaning */ if (p == pe) return FNM_NOMATCH; if ((flags & FNM_NOESCAPE) == 0) { c = *p++; /* A trailing `\' cannot match. */ if (p > pe) return FNM_NOMATCH; c = FOLD (c); } if (FOLD (sc) != (U_CHAR)c) return FNM_NOMATCH; break; case '*': /* Match zero or more characters */ if (p == pe) return 0; if ((flags & FNM_PERIOD) && sc == L('.') && (n == string || ((flags & FNM_PATHNAME) && n[-1] == L('/')))) /* `*' cannot match a `.' if it is the first character of the string or if it is the first character following a slash and we are matching a pathname. */ return FNM_NOMATCH; /* Collapse multiple consecutive `*' and `?', but make sure that one character of the string is consumed for each `?'. */ for (c = *p++; (c == L('?') || c == L('*')); c = *p++) { if ((flags & FNM_PATHNAME) && sc == L('/')) /* A slash does not match a wildcard under FNM_PATHNAME. */ return FNM_NOMATCH; else if (c == L('?')) { if (sc == L('\0')) return FNM_NOMATCH; /* One character of the string is consumed in matching this ? wildcard, so *??? won't match if there are fewer than three characters. */ n++; sc = n < se ? *n : '\0'; } #ifdef EXTENDED_GLOB /* Handle ******(patlist) */ if ((flags & FNM_EXTMATCH) && c == L('*') && *p == L('(')) /*)*/ { CHAR *newn; /* We need to check whether or not the extended glob pattern matches the remainder of the string. If it does, we match the entire pattern. */ for (newn = n; newn < se; ++newn) { if (EXTMATCH (c, newn, se, p, pe, flags) == 0) return (0); } /* We didn't match the extended glob pattern, but that's OK, since we can match 0 or more occurrences. We need to skip the glob pattern and see if we match the rest of the string. */ newn = PATSCAN (p + 1, pe, 0); /* If NEWN is 0, we have an ill-formed pattern. */ p = newn ? newn : pe; } #endif if (p == pe) break; } /* If we've hit the end of the pattern and the last character of the pattern was handled by the loop above, we've succeeded. Otherwise, we need to match that last character. */ if (p == pe && (c == L('?') || c == L('*'))) return (0); /* General case, use recursion. */ { U_CHAR c1; c1 = ((flags & FNM_NOESCAPE) == 0 && c == L('\\')) ? *p : c; c1 = FOLD (c1); for (--p; n < se; ++n) { /* Only call strmatch if the first character indicates a possible match. We can check the first character if we're not doing an extended glob match. */ if ((flags & FNM_EXTMATCH) == 0 && c != L('[') && FOLD (*n) != c1) /*]*/ continue; /* If we're doing an extended glob match and the pattern is not one of the extended glob patterns, we can check the first character. */ if ((flags & FNM_EXTMATCH) && p[1] != L('(') && /*)*/ STRCHR (L("?*+@!"), *p) == 0 && c != L('[') && FOLD (*n) != c1) /*]*/ continue; /* Otherwise, we just recurse. */ if (GMATCH (n, se, p, pe, flags & ~FNM_PERIOD) == 0) return (0); } return FNM_NOMATCH; } case L('['): { if (sc == L('\0') || n == se) return FNM_NOMATCH; /* A character class cannot match a `.' if it is the first character of the string or if it is the first character following a slash and we are matching a pathname. */ if ((flags & FNM_PERIOD) && sc == L('.') && (n == string || ((flags & FNM_PATHNAME) && n[-1] == L('/')))) return (FNM_NOMATCH); p = BRACKMATCH (p, sc, flags); if (p == 0) return FNM_NOMATCH; } break; default: if ((U_CHAR)c != FOLD (sc)) return (FNM_NOMATCH); } ++n; } if (n == se) return (0); if ((flags & FNM_LEADING_DIR) && *n == L('/')) /* The FNM_LEADING_DIR flag says that "foo*" matches "foobar/frobozz". */ return 0; return (FNM_NOMATCH); } /* Parse a bracket expression collating symbol ([.sym.]) starting at P, find the value of the symbol, and move P past the collating symbol expression. The value is returned in *VP, if VP is not null. */ static CHAR * PARSE_COLLSYM (p, vp) CHAR *p; INT *vp; { register int pc; INT val; p++; /* move past the `.' */ for (pc = 0; p[pc]; pc++) if (p[pc] == L('.') && p[pc+1] == L(']')) break; val = COLLSYM (p, pc); if (vp) *vp = val; return (p + pc + 2); } /* Use prototype definition here because of type promotion. */ static CHAR * #if defined (PROTOTYPES) BRACKMATCH (CHAR *p, U_CHAR test, int flags) #else BRACKMATCH (p, test, flags) CHAR *p; U_CHAR test; int flags; #endif { register CHAR cstart, cend, c; register int not; /* Nonzero if the sense of the character class is inverted. */ int brcnt; INT pc; CHAR *savep; test = FOLD (test); savep = p; /* POSIX.2 3.13.1 says that an exclamation mark (`!') shall replace the circumflex (`^') in its role in a `nonmatching list'. A bracket expression starting with an unquoted circumflex character produces unspecified results. This implementation treats the two identically. */ if (not = (*p == L('!') || *p == L('^'))) ++p; c = *p++; for (;;) { /* Initialize cstart and cend in case `-' is the last character of the pattern. */ cstart = cend = c; /* POSIX.2 equivalence class: [=c=]. See POSIX.2 2.8.3.2. Find the end of the equivalence class, move the pattern pointer past it, and check for equivalence. XXX - this handles only single-character equivalence classes, which is wrong, or at least incomplete. */ if (c == L('[') && *p == L('=') && p[2] == L('=') && p[3] == L(']')) { pc = FOLD (p[1]); p += 4; if (COLLEQUIV (test, pc)) { /*[*/ /* Move past the closing `]', since the first thing we do at the `matched:' label is back p up one. */ p++; goto matched; } else { c = *p++; if (c == L('\0')) return ((test == L('[')) ? savep : (CHAR *)0); /*]*/ c = FOLD (c); continue; } } /* POSIX.2 character class expression. See POSIX.2 2.8.3.2. */ if (c == L('[') && *p == L(':')) { CHAR *close, *ccname; pc = 0; /* make sure invalid char classes don't match. */ /* Find end of character class name */ for (close = p + 1; *close != '\0'; close++) if (*close == L(':') && *(close+1) == L(']')) break; if (*close != L('\0')) { ccname = (CHAR *)malloc ((close - p) * sizeof (CHAR)); if (ccname == 0) pc = 0; else { bcopy (p + 1, ccname, (close - p - 1) * sizeof (CHAR)); *(ccname + (close - p - 1)) = L('\0'); pc = IS_CCLASS (test, ccname); } if (pc == -1) pc = 0; else p = close + 2; free (ccname); } if (pc) { /*[*/ /* Move past the closing `]', since the first thing we do at the `matched:' label is back p up one. */ p++; goto matched; } else { /* continue the loop here, since this expression can't be the first part of a range expression. */ c = *p++; if (c == L('\0')) return ((test == L('[')) ? savep : (CHAR *)0); else if (c == L(']')) break; c = FOLD (c); continue; } } /* POSIX.2 collating symbols. See POSIX.2 2.8.3.2. Find the end of the symbol name, make sure it is terminated by `.]', translate the name to a character using the external table, and do the comparison. */ if (c == L('[') && *p == L('.')) { p = PARSE_COLLSYM (p, &pc); /* An invalid collating symbol cannot be the first point of a range. If it is, we set cstart to one greater than `test', so any comparisons later will fail. */ cstart = (pc == INVALID) ? test + 1 : pc; } if (!(flags & FNM_NOESCAPE) && c == L('\\')) { if (*p == '\0') return (CHAR *)0; cstart = cend = *p++; } cstart = cend = FOLD (cstart); /* POSIX.2 2.8.3.1.2 says: `An expression containing a `[' that is not preceded by a backslash and is not part of a bracket expression produces undefined results.' This implementation treats the `[' as just a character to be matched if there is not a closing `]'. */ if (c == L('\0')) return ((test == L('[')) ? savep : (CHAR *)0); c = *p++; c = FOLD (c); if ((flags & FNM_PATHNAME) && c == L('/')) /* [/] can never match when matching a pathname. */ return (CHAR *)0; /* This introduces a range, unless the `-' is the last character of the class. Find the end of the range and move past it. */ if (c == L('-') && *p != L(']')) { cend = *p++; if (!(flags & FNM_NOESCAPE) && cend == L('\\')) cend = *p++; if (cend == L('\0')) return (CHAR *)0; if (cend == L('[') && *p == L('.')) { p = PARSE_COLLSYM (p, &pc); /* An invalid collating symbol cannot be the second part of a range expression. If we get one, we set cend to one fewer than the test character to make sure the range test fails. */ cend = (pc == INVALID) ? test - 1 : pc; } cend = FOLD (cend); c = *p++; /* POSIX.2 2.8.3.2: ``The ending range point shall collate equal to or higher than the starting range point; otherwise the expression shall be treated as invalid.'' Note that this applies to only the range expression; the rest of the bracket expression is still checked for matches. */ if (RANGECMP (cstart, cend) > 0) { if (c == L(']')) break; c = FOLD (c); continue; } } if (RANGECMP (test, cstart) >= 0 && RANGECMP (test, cend) <= 0) goto matched; if (c == L(']')) break; } /* No match. */ return (!not ? (CHAR *)0 : p); matched: /* Skip the rest of the [...] that already matched. */ c = *--p; brcnt = 1; while (brcnt > 0) { /* A `[' without a matching `]' is just another character to match. */ if (c == L('\0')) return ((test == L('[')) ? savep : (CHAR *)0); c = *p++; if (c == L('[') && (*p == L('=') || *p == L(':') || *p == L('.'))) brcnt++; else if (c == L(']')) brcnt--; else if (!(flags & FNM_NOESCAPE) && c == L('\\')) { if (*p == '\0') return (CHAR *)0; /* XXX 1003.2d11 is unclear if this is right. */ ++p; } } return (not ? (CHAR *)0 : p); } #if defined (EXTENDED_GLOB) /* ksh-like extended pattern matching: [?*+@!](pat-list) where pat-list is a list of one or patterns separated by `|'. Operation is as follows: ?(patlist) match zero or one of the given patterns *(patlist) match zero or more of the given patterns +(patlist) match one or more of the given patterns @(patlist) match exactly one of the given patterns !(patlist) match anything except one of the given patterns */ /* Scan a pattern starting at STRING and ending at END, keeping track of embedded () and []. If DELIM is 0, we scan until a matching `)' because we're scanning a `patlist'. Otherwise, we scan until we see DELIM. In all cases, we never scan past END. The return value is the first character after the matching DELIM. */ static CHAR * PATSCAN (string, end, delim) CHAR *string, *end; INT delim; { int pnest, bnest; INT cchar; CHAR *s, c, *bfirst; pnest = bnest = 0; cchar = 0; bfirst = NULL; for (s = string; c = *s; s++) { if (s >= end) return (s); switch (c) { case L('\0'): return ((CHAR *)NULL); /* `[' is not special inside a bracket expression, but it may introduce one of the special POSIX bracket expressions ([.SYM.], [=c=], [: ... :]) that needs special handling. */ case L('['): if (bnest == 0) { bfirst = s + 1; if (*bfirst == L('!') || *bfirst == L('^')) bfirst++; bnest++; } else if (s[1] == L(':') || s[1] == L('.') || s[1] == L('=')) cchar = s[1]; break; /* `]' is not special if it's the first char (after a leading `!' or `^') in a bracket expression or if it's part of one of the special POSIX bracket expressions ([.SYM.], [=c=], [: ... :]) */ case L(']'): if (bnest) { if (cchar && s[-1] == cchar) cchar = 0; else if (s != bfirst) { bnest--; bfirst = 0; } } break; case L('('): if (bnest == 0) pnest++; break; case L(')'): if (bnest == 0 && pnest-- <= 0) return ++s; break; case L('|'): if (bnest == 0 && pnest == 0 && delim == L('|')) return ++s; break; } } return (NULL); } /* Return 0 if dequoted pattern matches S in the current locale. */ static int STRCOMPARE (p, pe, s, se) CHAR *p, *pe, *s, *se; { int ret; CHAR c1, c2; c1 = *pe; c2 = *se; *pe = *se = '\0'; #if HAVE_MULTIBYTE || defined (HAVE_STRCOLL) ret = STRCOLL ((XCHAR *)p, (XCHAR *)s); #else ret = STRCMP ((XCHAR *)p, (XCHAR *)s); #endif *pe = c1; *se = c2; return (ret == 0 ? ret : FNM_NOMATCH); } /* Match a ksh extended pattern specifier. Return FNM_NOMATCH on failure or 0 on success. This is handed the entire rest of the pattern and string the first time an extended pattern specifier is encountered, so it calls gmatch recursively. */ static int EXTMATCH (xc, s, se, p, pe, flags) INT xc; /* select which operation */ CHAR *s, *se; CHAR *p, *pe; int flags; { CHAR *prest; /* pointer to rest of pattern */ CHAR *psub; /* pointer to sub-pattern */ CHAR *pnext; /* pointer to next sub-pattern */ CHAR *srest; /* pointer to rest of string */ int m1, m2; #if DEBUG_MATCHING fprintf(stderr, "extmatch: xc = %c\n", xc); fprintf(stderr, "extmatch: s = %s; se = %s\n", s, se); fprintf(stderr, "extmatch: p = %s; pe = %s\n", p, pe); #endif prest = PATSCAN (p + (*p == L('(')), pe, 0); /* ) */ if (prest == 0) /* If PREST is 0, we failed to scan a valid pattern. In this case, we just want to compare the two as strings. */ return (STRCOMPARE (p - 1, pe, s, se)); switch (xc) { case L('+'): /* match one or more occurrences */ case L('*'): /* match zero or more occurrences */ /* If we can get away with no matches, don't even bother. Just call GMATCH on the rest of the pattern and return success if it succeeds. */ if (xc == L('*') && (GMATCH (s, se, prest, pe, flags) == 0)) return 0; /* OK, we have to do this the hard way. First, we make sure one of the subpatterns matches, then we try to match the rest of the string. */ for (psub = p + 1; ; psub = pnext) { pnext = PATSCAN (psub, pe, L('|')); for (srest = s; srest <= se; srest++) { /* Match this substring (S -> SREST) against this subpattern (psub -> pnext - 1) */ m1 = GMATCH (s, srest, psub, pnext - 1, flags) == 0; /* OK, we matched a subpattern, so make sure the rest of the string matches the rest of the pattern. Also handle multiple matches of the pattern. */ if (m1) m2 = (GMATCH (srest, se, prest, pe, flags) == 0) || (s != srest && GMATCH (srest, se, p - 1, pe, flags) == 0); if (m1 && m2) return (0); } if (pnext == prest) break; } return (FNM_NOMATCH); case L('?'): /* match zero or one of the patterns */ case L('@'): /* match exactly one of the patterns */ /* If we can get away with no matches, don't even bother. Just call gmatch on the rest of the pattern and return success if it succeeds. */ if (xc == L('?') && (GMATCH (s, se, prest, pe, flags) == 0)) return 0; /* OK, we have to do this the hard way. First, we see if one of the subpatterns matches, then, if it does, we try to match the rest of the string. */ for (psub = p + 1; ; psub = pnext) { pnext = PATSCAN (psub, pe, L('|')); srest = (prest == pe) ? se : s; for ( ; srest <= se; srest++) { if (GMATCH (s, srest, psub, pnext - 1, flags) == 0 && GMATCH (srest, se, prest, pe, flags) == 0) return (0); } if (pnext == prest) break; } return (FNM_NOMATCH); case '!': /* match anything *except* one of the patterns */ for (srest = s; srest <= se; srest++) { m1 = 0; for (psub = p + 1; ; psub = pnext) { pnext = PATSCAN (psub, pe, L('|')); /* If one of the patterns matches, just bail immediately. */ if (m1 = (GMATCH (s, srest, psub, pnext - 1, flags) == 0)) break; if (pnext == prest) break; } if (m1 == 0 && GMATCH (srest, se, prest, pe, flags) == 0) return (0); } return (FNM_NOMATCH); } return (FNM_NOMATCH); } #endif /* EXTENDED_GLOB */ #undef IS_CCLASS #undef FOLD #undef CHAR #undef U_CHAR #undef XCHAR #undef INT #undef INVALID #undef FCT #undef GMATCH #undef COLLSYM #undef PARSE_COLLSYM #undef PATSCAN #undef STRCOMPARE #undef EXTMATCH #undef BRACKMATCH #undef STRCHR #undef STRCOLL #undef STRLEN #undef STRCMP #undef COLLEQUIV #undef RANGECMP #undef L --- NEW FILE: glob.h --- /* File-name wildcard pattern matching for GNU. Copyright (C) 1985, 1988, 1989 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #ifndef _GLOB_H_ #define _GLOB_H_ #include "stdc.h" #define GX_MARKDIRS 0x01 /* mark directory names with trailing `/' */ #define GX_NOCASE 0x02 /* ignore case */ #define GX_MATCHDOT 0x04 /* match `.' literally */ extern int glob_pattern_p __P((const char *)); extern char **glob_vector __P((char *, char *, int)); extern char **glob_filename __P((char *, int)); extern char *glob_error_return; extern int noglob_dot_filenames; extern int glob_ignore_case; #endif /* _GLOB_H_ */ --- NEW FILE: Makefile.in --- ## -*- text -*- #################################################### # # # Makefile for the GNU Glob Library. # # # #################################################################### # # Copyright (C) 1996 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. srcdir = @srcdir@ VPATH = .:@srcdir@ topdir = @top_srcdir@ BUILD_DIR = @BUILD_DIR@ INSTALL = @INSTALL@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_DATA = @INSTALL_DATA@ CC = @CC@ RANLIB = @RANLIB@ AR = @AR@ ARFLAGS = @ARFLAGS@ RM = rm CP = cp MV = mv SHELL = @MAKE_SHELL@ PROFILE_FLAGS = @PROFILE_FLAGS@ CFLAGS = @CFLAGS@ LOCAL_CFLAGS = @LOCAL_CFLAGS@ CPPFLAGS = @CPPFLAGS@ LDFLAGS = @LDFLAGS@ @LOCAL_LDFLAGS@ DEFS = @DEFS@ LOCAL_DEFS = @LOCAL_DEFS@ BASHINCDIR = ${topdir}/include INCLUDES = -I. -I../.. -I$(topdir) -I$(BASHINCDIR) -I$(topdir)/lib CCFLAGS = $(PROFILE_FLAGS) $(DEFS) $(LOCAL_DEFS) $(CPPFLAGS) ${INCLUDES} \ $(LOCAL_CFLAGS) $(CFLAGS) # Here is a rule for making .o files from .c files that doesn't force # the type of the machine (like -sun3) into the flags. .c.o: $(CC) -c $(CCFLAGS) $< # The name of the library target. LIBRARY_NAME = libglob.a # The C code source files for this library. CSOURCES = $(srcdir)/glob.c $(srcdir)/strmatch.c $(srcdir)/smatch.c \ $(srcdir)/xmbsrtowcs.c # The header files for this library. HSOURCES = $(srcdir)/strmatch.h OBJECTS = glob.o strmatch.o smatch.o xmbsrtowcs.o # The texinfo files which document this library. DOCSOURCE = doc/glob.texi DOCOBJECT = doc/glob.dvi DOCSUPPORT = doc/Makefile DOCUMENTATION = $(DOCSOURCE) $(DOCOBJECT) $(DOCSUPPORT) SUPPORT = Makefile ChangeLog $(DOCSUPPORT) SOURCES = $(CSOURCES) $(HSOURCES) $(DOCSOURCE) THINGS_TO_TAR = $(SOURCES) $(SUPPORT) ###################################################################### all: $(LIBRARY_NAME) $(LIBRARY_NAME): $(OBJECTS) $(RM) -f $@ $(AR) $(ARFLAGS) $@ $(OBJECTS) -test -n "$(RANLIB)" && $(RANLIB) $@ what-tar: @for file in $(THINGS_TO_TAR); do \ echo $(selfdir)$$file; \ done documentation: force -(cd doc; $(MAKE) $(MFLAGS)) force: # The rule for 'includes' is written funny so that the if statement # always returns TRUE unless there really was an error installing the # include files. install: clean: rm -f $(OBJECTS) $(LIBRARY_NAME) -(cd doc && $(MAKE) $(MFLAGS) $@ ) realclean distclean maintainer-clean: clean -( cd doc && $(MAKE) $(MFLAGS) $@ ) $(RM) -f Makefile mostlyclean: clean -( cd doc && $(MAKE) $(MFLAGS) $@ ) ###################################################################### # # # Dependencies for the object files which make up this library. # # # ###################################################################### smatch.o: strmatch.h smatch.o: $(BUILD_DIR)/config.h smatch.o: $(BASHINCDIR)/chartypes.h smatch.o: $(BASHINCDIR)/ansi_stdlib.h $(topdir)/bashansi.h smatch.o: $(BASHINCDIR)/shmbutil.h smatch.o: $(topdir)/xmalloc.h strmatch.o: strmatch.h strmatch.o: $(BUILD_DIR)/config.h strmatch.o: $(BASHINCDIR)/stdc.h glob.o: $(BUILD_DIR)/config.h glob.o: $(topdir)/bashtypes.h $(BASHINCDIR)/ansi_stdlib.h $(topdir)/bashansi.h glob.o: $(BASHINCDIR)/posixstat.h $(BASHINCDIR)/memalloc.h glob.o: strmatch.h glob.h glob.o: $(BASHINCDIR)/shmbutil.h glob.o: $(topdir)/xmalloc.h xmbsrtowcs.o: ${BUILD_DIR}/config.h xmbsrtowcs.o: ${topdir}/bashansi.h ${BASHINCDIR}/ansi_stdlib.h xmbsrtowcs.o: ${BASHINCDIR}/shmbutil.h # Rules for deficient makes, like SunOS and Solaris glob.o: glob.c strmatch.o: strmatch.c smatch.o: smatch.c xmbsrtowcs.o: xmbsrtowcs.c # dependencies for C files that include other C files glob.o: glob_loop.c smatch.o: sm_loop.c --- NEW FILE: glob_loop.c --- /* Copyright (C) 1991-2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ static int INTERNAL_GLOB_PATTERN_P __P((const CHAR *)); /* Return nonzero if PATTERN has any special globbing chars in it. Compiled twice, once each for single-byte and multibyte characters. */ static int INTERNAL_GLOB_PATTERN_P (pattern) const CHAR *pattern; { register const CHAR *p; register CHAR c; int bopen; p = pattern; bopen = 0; while ((c = *p++) != L('\0')) switch (c) { case L('?'): case L('*'): return 1; case L('['): /* Only accept an open brace if there is a close */ bopen++; /* brace to match it. Bracket expressions must be */ continue; /* complete, according to Posix.2 */ case L(']'): if (bopen) return 1; continue; case L('+'): /* extended matching operators */ case L('@'): case L('!'): if (*p == L('(')) /*) */ return 1; continue; case L('\\'): if (*p++ == L('\0')) return 0; } return 0; } #undef INTERNAL_GLOB_PATTERN_P #undef L #undef INT #undef CHAR --- NEW FILE: smatch.c --- /* strmatch.c -- ksh-like extended pattern matching for the shell and filename globbing. */ /* Copyright (C) 1991-2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #include <stdio.h> /* for debugging */ #include "strmatch.h" #include <chartypes.h> #include "bashansi.h" #include "shmbutil.h" #include "xmalloc.h" /* First, compile `sm_loop.c' for single-byte characters. */ #define CHAR unsigned char #define U_CHAR unsigned char #define XCHAR char #define INT int #define L(CS) CS #define INVALID -1 #undef STREQ #undef STREQN #define STREQ(a, b) ((a)[0] == (b)[0] && strcmp(a, b) == 0) #define STREQN(a, b, n) ((a)[0] == (b)[0] && strncmp(a, b, n) == 0) /* We use strcoll(3) for range comparisons in bracket expressions, even though it can have unwanted side effects in locales other than POSIX or US. For instance, in the de locale, [A-Z] matches all characters. */ #if defined (HAVE_STRCOLL) /* Helper function for collating symbol equivalence. */ static int rangecmp (c1, c2) int c1, c2; { static char s1[2] = { ' ', '\0' }; static char s2[2] = { ' ', '\0' }; int ret; /* Eight bits only. Period. */ c1 &= 0xFF; c2 &= 0xFF; if (c1 == c2) return (0); s1[0] = c1; s2[0] = c2; if ((ret = strcoll (s1, s2)) != 0) return ret; return (c1 - c2); } #else /* !HAVE_STRCOLL */ # define rangecmp(c1, c2) ((int)(c1) - (int)(c2)) #endif /* !HAVE_STRCOLL */ #if defined (HAVE_STRCOLL) static int collequiv (c1, c2) int c1, c2; { return (rangecmp (c1, c2) == 0); } #else # define collequiv(c1, c2) ((c1) == (c2)) #endif #define _COLLSYM _collsym #define __COLLSYM __collsym #define POSIXCOLL posix_collsyms #include "collsyms.h" static int collsym (s, len) char *s; int len; { register struct _collsym *csp; for (csp = posix_collsyms; csp->name; csp++) { if (STREQN(csp->name, s, len) && csp->name[len] == '\0') return (csp->code); } if (len == 1) return s[0]; return INVALID; } /* unibyte character classification */ #if !defined (isascii) && !defined (HAVE_ISASCII) # define isascii(c) ((unsigned int)(c) <= 0177) #endif enum char_class { CC_NO_CLASS = 0, CC_ASCII, CC_ALNUM, CC_ALPHA, CC_BLANK, CC_CNTRL, CC_DIGIT, CC_GRAPH, CC_LOWER, CC_PRINT, CC_PUNCT, CC_SPACE, CC_UPPER, CC_WORD, CC_XDIGIT }; static char const *const cclass_name[] = { "", "ascii", "alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower", "print", "punct", "space", "upper", "word", "xdigit" }; #define N_CHAR_CLASS (sizeof(cclass_name) / sizeof (cclass_name[0])) static int is_cclass (c, name) int c; const char *name; { enum char_class char_class = CC_NO_CLASS; int i, result; for (i = 1; i < N_CHAR_CLASS; i++) { if (STREQ (name, cclass_name[i])) { char_class = (enum char_class)i; break; } } if (char_class == 0) return -1; switch (char_class) { case CC_ASCII: result = isascii (c); break; case CC_ALNUM: result = ISALNUM (c); break; case CC_ALPHA: result = ISALPHA (c); break; case CC_BLANK: result = ISBLANK (c); break; case CC_CNTRL: result = ISCNTRL (c); break; case CC_DIGIT: result = ISDIGIT (c); break; case CC_GRAPH: result = ISGRAPH (c); break; case CC_LOWER: result = ISLOWER (c); break; case CC_PRINT: result = ISPRINT (c); break; case CC_PUNCT: result = ISPUNCT (c); break; case CC_SPACE: result = ISSPACE (c); break; case CC_UPPER: result = ISUPPER (c); break; case CC_WORD: result = (ISALNUM (c) || c == '_'); break; case CC_XDIGIT: result = ISXDIGIT (c); break; default: result = -1; break; } return result; } /* Now include `sm_loop.c' for single-byte characters. */ /* The result of FOLD is an `unsigned char' */ # define FOLD(c) ((flags & FNM_CASEFOLD) \ ? TOLOWER ((unsigned char)c) \ : ((unsigned char)c)) #define FCT internal_strmatch #define GMATCH gmatch #define COLLSYM collsym #define PARSE_COLLSYM parse_collsym #define BRACKMATCH brackmatch #define PATSCAN patscan #define STRCOMPARE strcompare #define EXTMATCH extmatch #define STRCHR(S, C) strchr((S), (C)) #define STRCOLL(S1, S2) strcoll((S1), (S2)) #define STRLEN(S) strlen(S) #define STRCMP(S1, S2) strcmp((S1), (S2)) #define RANGECMP(C1, C2) rangecmp((C1), (C2)) #define COLLEQUIV(C1, C2) collequiv((C1), (C2)) #define CTYPE_T enum char_class #define IS_CCLASS(C, S) is_cclass((C), (S)) #include "sm_loop.c" #if HANDLE_MULTIBYTE # define CHAR wchar_t # define U_CHAR wint_t # define XCHAR wchar_t # define INT wint_t # define L(CS) L##CS # define INVALID WEOF # undef STREQ # undef STREQN # define STREQ(s1, s2) ((wcscmp (s1, s2) == 0)) # define STREQN(a, b, n) ((a)[0] == (b)[0] && wcsncmp(a, b, n) == 0) static int rangecmp_wc (c1, c2) wint_t c1, c2; { static wchar_t s1[2] = { L' ', L'\0' }; static wchar_t s2[2] = { L' ', L'\0' }; int ret; if (c1 == c2) return 0; s1[0] = c1; s2[0] = c2; return (wcscoll (s1, s2)); } static int collequiv_wc (c, equiv) wint_t c, equiv; { return (!(c - equiv)); } /* Helper function for collating symbol. */ # define _COLLSYM _collwcsym # define __COLLSYM __collwcsym # define POSIXCOLL posix_collwcsyms # include "collsyms.h" static wint_t collwcsym (s, len) wchar_t *s; int len; { register struct _collwcsym *csp; for (csp = posix_collwcsyms; csp->name; csp++) { if (STREQN(csp->name, s, len) && csp->name[len] == L'\0') return (csp->code); } if (len == 1) return s[0]; return INVALID; } static int is_wcclass (wc, name) wint_t wc; wchar_t *name; { char *mbs; mbstate_t state; size_t mbslength; wctype_t desc; int want_word; if ((wctype ("ascii") == (wctype_t)0) && (wcscmp (name, L"ascii") == 0)) { int c; if ((c = wctob (wc)) == EOF) return 0; else return (c <= 0x7F); } want_word = (wcscmp (name, L"word") == 0); if (want_word) name = L"alnum"; memset (&state, '\0', sizeof (mbstate_t)); mbs = (char *) malloc (wcslen(name) * MB_CUR_MAX + 1); mbslength = wcsrtombs(mbs, (const wchar_t **)&name, (wcslen(name) * MB_CUR_MAX + 1), &state); if (mbslength == (size_t)-1 || mbslength == (size_t)-2) { free (mbs); return -1; } desc = wctype (mbs); free (mbs); if (desc == (wctype_t)0) return -1; if (want_word) return (iswctype (wc, desc) || wc == L'_'); else return (iswctype (wc, desc)); } /* Now include `sm_loop.c' for multibyte characters. */ #define FOLD(c) ((flags & FNM_CASEFOLD) && iswupper (c) ? towlower (c) : (c)) #define FCT internal_wstrmatch #define GMATCH gmatch_wc #define COLLSYM collwcsym #define PARSE_COLLSYM parse_collwcsym #define BRACKMATCH brackmatch_wc #define PATSCAN patscan_wc #define STRCOMPARE wscompare #define EXTMATCH extmatch_wc #define STRCHR(S, C) wcschr((S), (C)) #define STRCOLL(S1, S2) wcscoll((S1), (S2)) #define STRLEN(S) wcslen(S) #define STRCMP(S1, S2) wcscmp((S1), (S2)) #define RANGECMP(C1, C2) rangecmp_wc((C1), (C2)) #define COLLEQUIV(C1, C2) collequiv_wc((C1), (C2)) #define CTYPE_T enum char_class #define IS_CCLASS(C, S) is_wcclass((C), (S)) #include "sm_loop.c" #endif /* HAVE_MULTIBYTE */ int xstrmatch (pattern, string, flags) char *pattern; char *string; int flags; { #if HANDLE_MULTIBYTE int ret; mbstate_t ps; size_t n; char *pattern_bak; wchar_t *wpattern, *wstring; if (MB_CUR_MAX == 1) return (internal_strmatch (pattern, string, flags)); pattern_bak = (char *)xmalloc (strlen (pattern) + 1); strcpy (pattern_bak, pattern); memset (&ps, '\0', sizeof (mbstate_t)); n = xmbsrtowcs (NULL, (const char **)&pattern, 0, &ps); if (n == (size_t)-1 || n == (size_t)-2) { free (pattern_bak); return (internal_strmatch ((unsigned char *)pattern, (unsigned char *)string, flags)); } wpattern = (wchar_t *)xmalloc ((n + 1) * sizeof (wchar_t)); (void) xmbsrtowcs (wpattern, (const char **)&pattern, n + 1, &ps); memset (&ps, '\0', sizeof (mbstate_t)); n = xmbsrtowcs (NULL, (const char **)&string, 0, &ps); if (n == (size_t)-1 || n == (size_t)-2) { free (wpattern); ret = internal_strmatch (pattern_bak, string, flags); free (pattern_bak); return ret; } wstring = (wchar_t *)xmalloc ((n + 1) * sizeof (wchar_t)); (void) xmbsrtowcs (wstring, (const char **)&string, n + 1, &ps); ret = internal_wstrmatch (wpattern, wstring, flags); free (pattern_bak); free (wpattern); free (wstring); return ret; #else return (internal_strmatch ((unsigned char *)pattern, (unsigned char *)string, flags)); #endif /* !HANDLE_MULTIBYTE */ } --- NEW FILE: strmatch.h --- /* Copyright (C) 1991 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #ifndef _STRMATCH_H #define _STRMATCH_H 1 #ifdef HAVE_LIBC_FNM_EXTMATCH #include <fnmatch.h> #else /* !HAVE_LIBC_FNM_EXTMATCH */ #include "stdc.h" /* We #undef these before defining them because some losing systems (HP-UX A.08.07 for example) define these in <unistd.h>. */ #undef FNM_PATHNAME #undef FNM_NOESCAPE #undef FNM_PERIOD /* Bits set in the FLAGS argument to `strmatch'. */ /* standard flags are like fnmatch(3). */ #define FNM_PATHNAME (1 << 0) /* No wildcard can ever match `/'. */ #define FNM_NOESCAPE (1 << 1) /* Backslashes don't quote special chars. */ #define FNM_PERIOD (1 << 2) /* Leading `.' is matched only explicitly. */ /* extended flags not available in most libc fnmatch versions, but we undef them to avoid any possible warnings. */ #undef FNM_LEADING_DIR #undef FNM_CASEFOLD #undef FNM_EXTMATCH #define FNM_LEADING_DIR (1 << 3) /* Ignore `/...' after a match. */ #define FNM_CASEFOLD (1 << 4) /* Compare without regard to case. */ #define FNM_EXTMATCH (1 << 5) /* Use ksh-like extended matching. */ /* Value returned by `strmatch' if STRING does not match PATTERN. */ #undef FNM_NOMATCH #define FNM_NOMATCH 1 /* Match STRING against the filename pattern PATTERN, returning zero if it matches, FNM_NOMATCH if not. */ extern int strmatch __P((char *, char *, int)); #endif /* !HAVE_LIBC_FNM_EXTMATCH */ #endif /* _STRMATCH_H */ --- NEW FILE: collsyms.h --- /* collsyms.h -- collating symbol names and their corresponding characters (in ascii) as given by POSIX.2 in table 2.8. */ /* Copyright (C) 1997-2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* The upper-case letters, lower-case letters, and digits are omitted from this table. The digits are not included in the table in the POSIX.2 spec. The upper and lower case letters are translated by the code in smatch.c:collsym(). */ typedef struct _COLLSYM { XCHAR *name; CHAR code; } __COLLSYM; static __COLLSYM POSIXCOLL [] = { { L("NUL"), L('\0') }, { L("SOH"), L('\001') }, { L("STX"), L('\002') }, { L("ETX"), L('\003') }, { L("EOT"), L('\004') }, { L("ENQ"), L('\005') }, { L("ACK"), L('\006') }, #ifdef __STDC__ { L("alert"), L('\a') }, #else { L("alert"), L('\007') }, #endif { L("BS"), L('\010') }, { L("backspace"), L('\b') }, { L("HT"), L('\011') }, { L("tab"), L('\t') }, { L("LF"), L('\012') }, { L("newline"), L('\n') }, { L("VT"), L('\013') }, { L("vertical-tab"), L('\v') }, { L("FF"), L('\014') }, { L("form-feed"), L('\f') }, { L("CR"), L('\015') }, { L("carriage-return"), L('\r') }, { L("SO"), L('\016') }, { L("SI"), L('\017') }, { L("DLE"), L('\020') }, { L("DC1"), L('\021') }, { L("DC2"), L('\022') }, { L("DC3"), L('\023') }, { L("DC4"), L('\024') }, { L("NAK"), L('\025') }, { L("SYN"), L('\026') }, { L("ETB"), L('\027') }, { L("CAN"), L('\030') }, { L("EM"), L('\031') }, { L("SUB"), L('\032') }, { L("ESC"), L('\033') }, { L("IS4"), L('\034') }, { L("FS"), L('\034') }, { L("IS3"), L('\035') }, { L("GS"), L('\035') }, { L("IS2"), L('\036') }, { L("RS"), L('\036') }, { L("IS1"), L('\037') }, { L("US"), L('\037') }, { L("space"), L(' ') }, { L("exclamation-mark"), L('!') }, { L("quotation-mark"), L('"') }, { L("number-sign"), L('#') }, { L("dollar-sign"), L('$') }, { L("percent-sign"), L('%') }, { L("ampersand"), L('&') }, { L("apostrophe"), L('\'') }, { L("left-parenthesis"), L('(') }, { L("right-parenthesis"), L(')') }, { L("asterisk"), L('*') }, { L("plus-sign"), L('+') }, { L("comma"), L(',') }, { L("hyphen"), L('-') }, { L("hyphen-minus"), L('-') }, { L("minus"), L('-') }, /* extension from POSIX.2 */ { L("dash"), L('-') }, /* extension from POSIX.2 */ { L("period"), L('.') }, { L("full-stop"), L('.') }, { L("slash"), L('/') }, { L("solidus"), L('/') }, /* extension from POSIX.2 */ { L("zero"), L('0') }, { L("one"), L('1') }, { L("two"), L('2') }, { L("three"), L('3') }, { L("four"), L('4') }, { L("five"), L('5') }, { L("six"), L('6') }, { L("seven"), L('7') }, { L("eight"), L('8') }, { L("nine"), L('9') }, { L("colon"), L(':') }, { L("semicolon"), L(';') }, { L("less-than-sign"), L('<') }, { L("equals-sign"), L('=') }, { L("greater-than-sign"), L('>') }, { L("question-mark"), L('?') }, { L("commercial-at"), L('@') }, /* upper-case letters omitted */ { L("left-square-bracket"), L('[') }, { L("backslash"), L('\\') }, { L("reverse-solidus"), L('\\') }, { L("right-square-bracket"), L(']') }, { L("circumflex"), L('^') }, { L("circumflex-accent"), L('^') }, /* extension from POSIX.2 */ { L("underscore"), L('_') }, { L("grave-accent"), L('`') }, /* lower-case letters omitted */ { L("left-brace"), L('{') }, /* extension from POSIX.2 */ { L("left-curly-bracket"), L('{') }, { L("vertical-line"), L('|') }, { L("right-brace"), L('}') }, /* extension from POSIX.2 */ { L("right-curly-bracket"), L('}') }, { L("tilde"), L('~') }, { L("DEL"), L('\177') }, { 0, 0 }, }; #undef _COLLSYM #undef __COLLSYM #undef POSIXCOLL --- NEW FILE: ndir.h --- /* <dir.h> -- definitions for 4.2BSD-compatible directory access. last edit: 09-Jul-1983 D A Gwyn. */ #if defined (VMS) # if !defined (FAB$C_BID) # include <fab.h> # endif # if !defined (NAM$C_BID) # include <nam.h> # endif # if !defined (RMS$_SUC) # include <rmsdef.h> # endif # include "dir.h" #endif /* VMS */ /* Size of directory block. */ #define DIRBLKSIZ 512 /* NOTE: MAXNAMLEN must be one less than a multiple of 4 */ #if defined (VMS) # define MAXNAMLEN (DIR$S_NAME + 7) /* 80 plus room for version #. */ # define MAXFULLSPEC NAM$C_MAXRSS /* Maximum full spec */ #else # define MAXNAMLEN 15 /* Maximum filename length. */ #endif /* VMS */ /* Data from readdir (). */ struct direct { long d_ino; /* Inode number of entry. */ unsigned short d_reclen; /* Length of this record. */ unsigned short d_namlen; /* Length of string in d_name. */ char d_name[MAXNAMLEN + 1]; /* Name of file. */ }; /* Stream data from opendir (). */ typedef struct { int dd_fd; /* File descriptor. */ int dd_loc; /* Offset in block. */ int dd_size; /* Amount of valid data. */ char dd_buf[DIRBLKSIZ]; /* Directory block. */ } DIR; extern DIR *opendir (); extern struct direct *readdir (); extern long telldir (); extern void seekdir (), closedir (); #define rewinddir(dirp) seekdir (dirp, 0L) --- NEW FILE: xmbsrtowcs.c --- /* xmbsrtowcs.c -- replacement function for mbsrtowcs */ /* Copyright (C) 2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #include <bashansi.h> /* <wchar.h>, <wctype.h> and <stdlib.h> are included in "shmbutil.h". If <wchar.h>, <wctype.h>, mbsrtowcs(), exist, HANDLE_MULTIBYTE is defined as 1. */ #include <shmbutil.h> #if HANDLE_MULTIBYTE /* On some locales (ex. ja_JP.sjis), mbsrtowc doesn't convert 0x5c to U<0x5c>. So, this function is made for converting 0x5c to U<0x5c>. */ static mbstate_t local_state; static int local_state_use = 0; size_t xmbsrtowcs (dest, src, len, pstate) wchar_t *dest; const char **src; size_t len; mbstate_t *pstate; { mbstate_t *ps; size_t mblength, wclength, n; ps = pstate; if (pstate == NULL) { if (!local_state_use) { memset (&local_state, '\0', sizeof(mbstate_t)); local_state_use = 1; } ps = &local_state; } n = strlen(*src) + 1; if (dest == NULL) { wchar_t *wsbuf; char *mbsbuf, *mbsbuf_top; mbstate_t psbuf; wsbuf = (wchar_t *) malloc ((n + 1) * sizeof(wchar_t)); mbsbuf_top = mbsbuf = (char *) malloc (n + 1); memcpy(mbsbuf, *src, n + 1); psbuf = *ps; wclength = mbsrtowcs (wsbuf, (const char **)&mbsbuf, n, &psbuf); free (wsbuf); free (mbsbuf_top); return wclength; } for(wclength = 0; wclength < len; wclength++, dest++) { if(mbsinit(ps)) { if (**src == '\0') { *dest = L'\0'; *src = NULL; return (wclength); } else if (**src == '\\') { *dest = L'\\'; mblength = 1; } else mblength = mbrtowc(dest, *src, n, ps); } else mblength = mbrtowc(dest, *src, n, ps); /* Cannot convert multibyte character to wide character. */ if (mblength == (size_t)-1 || mblength == (size_t)-2) return (size_t)-1; *src += mblength; n -= mblength; /* The multibyte string has been completely converted, including the terminating '\0'. */ if (*dest == L'\0') { *src = NULL; break; } } return (wclength); } #endif /* HANDLE_MULTIBYTE */ --- NEW FILE: strmatch.c --- /* strmatch.c -- ksh-like extended pattern matching for the shell and filename globbing. */ /* Copyright (C) 1991-2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #include "stdc.h" #include "strmatch.h" /* Structured this way so that if HAVE_LIBC_FNM_EXTMATCH is defined, the matching portion of the library (smatch.c) is not linked into the shell. */ #ifndef HAVE_LIBC_FNM_EXTMATCH extern int xstrmatch __P((char *, char *, int)); #else # define xstrmatch fnmatch #endif int strmatch (pattern, string, flags) char *pattern; char *string; int flags; { if (string == 0 || pattern == 0) return FNM_NOMATCH; return (xstrmatch (pattern, string, flags)); } #ifdef TEST main (c, v) int c; char **v; { char *string, *pat; string = v[1]; pat = v[2]; if (strmatch (pat, string, 0) == 0) { printf ("%s matches %s\n", string, pat); exit (0); } else { printf ("%s does not match %s\n", string, pat); exit (1); } } #endif --- NEW FILE: glob.c --- /* glob.c -- file-name wildcard pattern matching for Bash. Copyright (C) 1985-2002 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* To whomever it may concern: I have never seen the code which most Unix programs use to perform this function. I wrote this from scratch based on specifications for the pattern matching. --RMS. */ #include <config.h> #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX) #pragma alloca #endif /* _AIX && RISC6000 && !__GNUC__ */ #include "bashtypes.h" #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #include "bashansi.h" #include "posixdir.h" #include "posixstat.h" #include "shmbutil.h" #include "xmalloc.h" #include "filecntl.h" #if !defined (F_OK) # define F_OK 0 #endif #include "stdc.h" #include "memalloc.h" #include "quit.h" #include "glob.h" #include "strmatch.h" #if !defined (HAVE_BCOPY) && !defined (bcopy) # define bcopy(s, d, n) ((void) memcpy ((d), (s), (n))) #endif /* !HAVE_BCOPY && !bcopy */ #if !defined (NULL) # if defined (__STDC__) # define NULL ((void *) 0) # else # define NULL 0x0 # endif /* __STDC__ */ #endif /* !NULL */ extern void throw_to_top_level __P((void)); extern int test_eaccess __P((char *, int)); extern int extended_glob; /* Global variable which controls whether or not * matches .*. Non-zero means don't match .*. */ int noglob_dot_filenames = 1; /* Global variable which controls whether or not filename globbing is done without regard to case. */ int glob_ignore_case = 0; /* Global variable to return to signify an error in globbing. */ char *glob_error_return; /* Some forward declarations. */ static int skipname __P((char *, char *)); #if HANDLE_MULTIBYTE static int mbskipname __P((char *, char *)); #endif #if HANDLE_MULTIBYTE static void udequote_pathname __P((char *)); static void wdequote_pathname __P((char *)); #else # define dequote_pathname udequote_pathname #endif static void dequote_pathname __P((char *)); static int glob_testdir __P((char *)); static char **glob_dir_to_array __P((char *, char **, int)); /* Compile `glob_loop.c' for single-byte characters. */ #define CHAR unsigned char #define INT int #define L(CS) CS #define INTERNAL_GLOB_PATTERN_P internal_glob_pattern_p #include "glob_loop.c" /* Compile `glob_loop.c' again for multibyte characters. */ #if HANDLE_MULTIBYTE #define CHAR wchar_t #define INT wint_t #define L(CS) L##CS #define INTERNAL_GLOB_PATTERN_P internal_glob_wpattern_p #include "glob_loop.c" #endif /* HANDLE_MULTIBYTE */ /* And now a function that calls either the single-byte or multibyte version of internal_glob_pattern_p. */ int glob_pattern_p (pattern) const char *pattern; { #if HANDLE_MULTIBYTE mbstate_t ps; size_t n; wchar_t *wpattern; int r; if (MB_CUR_MAX == 1) return (internal_glob_pattern_p (pattern)); /* Convert strings to wide chars, and call the multibyte version. */ memset (&ps, '\0', sizeof (ps)); n = xmbsrtowcs (NULL, (const char **)&pattern, 0, &ps); if (n == (size_t)-1) /* Oops. Invalid multibyte sequence. Try it as single-byte sequence. */ return (internal_glob_pattern_p (pattern)); wpattern = (wchar_t *)xmalloc ((n + 1) * sizeof (wchar_t)); (void) xmbsrtowcs (wpattern, (const char **)&pattern, n + 1, &ps); r = internal_glob_wpattern_p (wpattern); free (wpattern); return r; #else return (internal_glob_pattern_p (pattern)); #endif } /* Return 1 if DNAME should be skipped according to PAT. Mostly concerned with matching leading `.'. */ static int skipname (pat, dname) char *pat; char *dname; { /* If a leading dot need not be explicitly matched, and the pattern doesn't start with a `.', don't match `.' or `..' */ if (noglob_dot_filenames == 0 && pat[0] != '.' && (pat[0] != '\\' || pat[1] != '.') && (dname[0] == '.' && (dname[1] == '\0' || (dname[1] == '.' && dname[2] == '\0')))) return 1; /* If a dot must be explicity matched, check to see if they do. */ else if (noglob_dot_filenames && dname[0] == '.' && pat[0] != '.' && (pat[0] != '\\' || pat[1] != '.')) return 1; return 0; } #if HANDLE_MULTIBYTE /* Return 1 if DNAME should be skipped according to PAT. Handles multibyte characters in PAT and DNAME. Mostly concerned with matching leading `.'. */ static int mbskipname (pat, dname) char *pat, *dname; { char *pat_bak, *dn_bak; wchar_t *pat_wc, *dn_wc; mbstate_t pat_ps, dn_ps; size_t pat_n, dn_n, n; n = strlen(pat); pat_bak = (char *) alloca (n + 1); memcpy (pat_bak, pat, n + 1); n = strlen(dname); dn_bak = (char *) alloca (n + 1); memcpy (dn_bak, dname, n + 1); memset(&pat_ps, '\0', sizeof(mbstate_t)); memset(&dn_ps, '\0', sizeof(mbstate_t)); pat_n = xmbsrtowcs (NULL, (const char **)&pat_bak, 0, &pat_ps); dn_n = xmbsrtowcs (NULL, (const char **)&dn_bak, 0, &dn_ps); if (pat_n != (size_t)-1 && dn_n !=(size_t)-1) { pat_wc = (wchar_t *) alloca ((pat_n + 1) * sizeof(wchar_t)); dn_wc = (wchar_t *) alloca ((dn_n + 1) * sizeof(wchar_t)); (void) xmbsrtowcs (pat_wc, (const char **)&pat_bak, pat_n + 1, &pat_ps); (void) xmbsrtowcs (dn_wc, (const char **)&dn_bak, dn_n + 1, &dn_ps); /* If a leading dot need not be explicitly matched, and the pattern doesn't start with a `.', don't match `.' or `..' */ if (noglob_dot_filenames == 0 && pat_wc[0] != L'.' && (pat_wc[0] != L'\\' || pat_wc[1] != L'.') && (dn_wc[0] == L'.' && (dn_wc[1] == L'\0' || (dn_wc[1] == L'.' && dn_wc[2] == L'\0')))) return 1; /* If a leading dot must be explicity matched, check to see if the pattern and dirname both have one. */ else if (noglob_dot_filenames && dn_wc[0] == L'.' && pat_wc[0] != L'.' && (pat_wc[0] != L'\\' || pat_wc[1] != L'.')) return 1; } return 0; } #endif /* HANDLE_MULTIBYTE */ /* Remove backslashes quoting characters in PATHNAME by modifying PATHNAME. */ static void udequote_pathname (pathname) char *pathname; { register int i, j; for (i = j = 0; pathname && pathname[i]; ) { if (pathname[i] == '\\') i++; pathname[j++] = pathname[i++]; if (!pathname[i - 1]) break; } pathname[j] = '\0'; } #if HANDLE_MULTIBYTE /* Remove backslashes quoting characters in PATHNAME by modifying PATHNAME. */ static void wdequote_pathname (pathname) char *pathname; { mbstate_t ps; size_t len, n; wchar_t *wpathname; char *pathname_bak; int i, j; len = strlen (pathname); pathname_bak = (char *) alloca (len + 1); memcpy (pathname_bak, pathname , len + 1); /* Convert the strings into wide characters. */ memset (&ps, '\0', sizeof (ps)); n = xmbsrtowcs (NULL, (const char **)&pathname_bak, 0, &ps); if (n == (size_t) -1) /* Something wrong. */ return; wpathname = (wchar_t *) alloca ((n + 1) * sizeof (wchar_t)); (void) xmbsrtowcs (wpathname, (const char **)&pathname_bak, n + 1, &ps); for (i = j = 0; wpathname && wpathname[i]; ) { if (wpathname[i] == L'\\') i++; wpathname[j++] = wpathname[i++]; if (!wpathname[i - 1]) break; } wpathname[j] = L'\0'; /* Convert the wide character string into unibyte character set. */ memset (&ps, '\0', sizeof(mbstate_t)); n = wcsrtombs(pathname, (const wchar_t **)&wpathname, len, &ps); pathname[len] = '\0'; } static void dequote_pathname (pathname) char *pathname; { if (MB_CUR_MAX > 1) wdequote_pathname (pathname); else udequote_pathname (pathname); } #endif /* HANDLE_MULTIBYTE */ /* Test whether NAME exists. */ #if defined (HAVE_LSTAT) # define GLOB_TESTNAME(name) (lstat (name, &finfo)) #else /* !HAVE_LSTAT */ # if !defined (AFS) # define GLOB_TESTNAME(name) (test_eaccess (nextname, F_OK)) # else /* AFS */ # define GLOB_TESTNAME(name) (access (nextname, F_OK)) # endif /* AFS */ #endif /* !HAVE_LSTAT */ /* Return 0 if DIR is a directory, -1 otherwise. */ static int glob_testdir (dir) char *dir; { struct stat finfo; if (stat (dir, &finfo) < 0) return (-1); if (S_ISDIR (finfo.st_mode) == 0) return (-1); return (0); } /* Return a vector of names of files in directory DIR whose names match glob pattern PAT. The names are not in any particular order. Wildcards at the beginning of PAT do not match an initial period. The vector is terminated by an element that is a null pointer. To free the space allocated, first free the vector's elements, then free the vector. Return 0 if cannot get enough memory to hold the pointer and the names. Return -1 if cannot access directory DIR. Look in errno for more information. */ char ** glob_vector (pat, dir, flags) char *pat; char *dir; int flags; { struct globval { struct globval *next; char *name; }; DIR *d; register struct dirent *dp; struct globval *lastlink; register struct globval *nextlink; register char *nextname, *npat; unsigned int count; int lose, skip; register char **name_vector; register unsigned int i; int mflags; /* Flags passed to strmatc... [truncated message content] |
Update of /cvsroot/mingw/msys/packages/bash/2.05b/support In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/support Added Files: Makefile.in SYMLINKS bash.xbm bashbug.sh bashversion.c config.guess config.sub fixlinks install.sh man2html.c missing mkclone mkconffiles mkdirs mksignames.c mkversion.sh printenv.c printenv.sh recho.c rlvers.sh shobj-conf texi2dvi texi2html xenix-link.sh zecho.c Log Message: Pristine source --- NEW FILE: SYMLINKS --- # # symlink map for bash source tree # # link name link target # lib/readline/tilde.c ../tilde/tilde.c lib/readline/tilde.h ../tilde/tilde.h # lib/readline/ansi_stdlib.h ../../include/ansi_stdlib.h lib/readline/posixdir.h ../../include/posixdir.h lib/readline/posixjmp.h ../../include/posixjmp.h lib/readline/posixstat.h ../../include/posixstat.h #lib/readline/rlstdc.h ../../include/stdc.h #lib/readline/xmalloc.c ../malloc/xmalloc.c # #lib/tilde/memalloc.h ../../include/memalloc.h # --- NEW FILE: fixlinks --- #! /bin/sh # # fixlinks - make symlinks in the bash source tree so that there is # exactly one version of any given source file. # # Copyright (C) 1996-2002 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. SRCDIR=. while [ $# -gt 0 ]; do case "$1" in -s) shift; SRCDIR=$1 ;; -u) unfix=yes ;; -h) hardlinks=yes ;; -*) echo "$0: $1: bad option" 1>&2 echo "$0: usage: $0 [-hu] [-s srcdir] [linkmap]" 1>&2 exit 1;; *) break ;; esac shift done if [ ! -d $SRCDIR/builtins ]; then echo "$0: must be run with valid -s argument or from source directory" 1>&2 exit 1 fi if [ $# -eq 0 ]; then linkfile=$SRCDIR/support/SYMLINKS else linkfile=$1 fi if [ ! -f "$linkfile" ]; then echo "$0: symlink map file \`$linkfile' does not exist" exit 1 fi rm_ltmp=false LINKTEMP=`mktemp -t linktmp.XXXXXXXX 2>/dev/null` if [ -z "$LINKTEMP" ]; then : ${TMPDIR:=/tmp} LINKTEMP=${TMPDIR}/linktmp.$$ rm_ltmp=true fi $rm_ltmp && rm -f ${LINKTEMP} # if the user specified hard links, then do that. otherwise, try to use # symlinks if they're present if [ -n "$hardlinks" ]; then LN=ln elif (ln -s /dev/null ${LINKTEMP}) >/dev/null 2>&1; then LN="ln -s" else LN=ln fi rm -f ${LINKTEMP} while read name target do case "$name" in \#*) continue;; esac rm -f $name case "$unfix" in yes) dirname=`expr "$name" ':' '^\(.*\)/[^/]*'` [ -z "$dirname" ] && dirname=. cp $dirname/$target $name echo $target copied to $name ;; *) $LN $target $name ; echo "$name -> $target" ;; esac done < $linkfile exit 0 --- NEW FILE: rlvers.sh --- #! /bin/sh # # rlvers.sh -- run a program that prints out the readline version number # using locally-installed readline libraries # # Copyright (C) 1996-2002 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. PROGNAME=`basename $0` : ${TMPDIR:=/tmp} TDIR=$TMPDIR/rlvers # defaults CC=cc RL_LIBDIR=/usr/local/lib RL_INCDIR=/usr/local/include TERMCAP_LIB="-ltermcap" # cannot rely on the presence of getopts while [ $# -gt 0 ]; do case "$1" in -C) shift ; CC="$1"; shift ;; -I) shift ; RL_INCDIR="$1" ; shift ;; -L) shift ; RL_LIBDIR="$1" ; shift ;; -T) shift ; TERMCAP_LIB="$1" ; shift ;; -v) shift ; verbose=y ;; --) shift ; break ;; *) echo "${PROGNAME}: usage: $PROGNAME [-C compiler] [-L libdir] [-v]" >&2 ; exit 2;; esac done # if someone happened to install examples/rlversion, use it (it's not # installed by default) if test -f ${RL_LIBDIR}/rlversion ; then if [ -n "$verbose" ]; then echo "${PROGNAME}: using installed rlversion from ${RL_LIBDIR}/rlversion" fi v=`${RL_LIBDIR}/rlversion 2>/dev/null` case "$v" in unknown | "") echo 0 ;; *) echo "$v" ;; esac exit 0 fi if [ -n "$verbose" ]; then echo "${PROGNAME}: using ${RL_LIBDIR} to find libreadline" echo "${PROGNAME}: attempting program compilation" fi # make $TDIR mode 0700 mkdir $TDIR || { echo "${PROGNAME}: ${TDIR}: file exists" >&2 echo 0 exit 1 } chmod 700 $TDIR trap 'rm -f $TDIR/rlvers $TDIR/rlvers.? ; rmdir $TDIR' 0 1 2 3 6 15 cat > $TDIR/rlvers.c << EOF #include <stdio.h> extern char *rl_library_version; main() { printf("%s\n", rl_library_version ? rl_library_version : "0"); exit(0); } EOF opwd=`pwd` cd $TDIR || { echo "${PROGNAME}: cannot cd to $TDIR" >&2 echo 0 exit 1 } if eval ${CC} -L${RL_LIBDIR} -I${RL_INCDIR} -o $TDIR/rlvers $TDIR/rlvers.c -lreadline ${TERMCAP_LIB}; then v=`$TDIR/rlvers` else if [ -n "$verbose" ] ; then echo "${PROGNAME}: compilation failed: status $?" echo "${PROGNAME}: using version 0" fi v=0 fi case "$v" in unknown | "") echo 0 ;; *) echo "$v" ;; esac cd $opwd exit 0 --- NEW FILE: missing --- #! /bin/sh # Common stub for a few missing GNU programs while installing. # Copyright (C) 1996, 1997 Free Software Foundation, Inc. # Franc,ois Pinard <pi...@ir...>, 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA # 02111-1307, USA. if test $# -eq 0; then echo 1>&2 "Try \`$0 --help' for more information" exit 1 fi case "$1" in -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an error status if there is no known handling for PROGRAM. Options: -h, --help display this help and exit -v, --version output version information and exit Supported PROGRAM values: aclocal touch file \`aclocal.m4' autoconf touch file \`configure' autoheader touch file \`config.h.in' automake touch all \`Makefile.in' files bison create \`y.tab.[ch]', if possible, from existing .[ch] flex create \`lex.yy.c', if possible, from existing .c lex create \`lex.yy.c', if possible, from existing .c makeinfo touch the output file yacc create \`y.tab.[ch]', if possible, from existing .[ch]" ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing - GNU libit 0.0" ;; -*) echo 1>&2 "$0: Unknown \`$1' option" echo 1>&2 "Try \`$0 --help' for more information" exit 1 ;; aclocal) echo 1>&2 "\ WARNING: \`$1' is missing on your system. You should only need it if you modified \`acinclude.m4' or \`configure.in'. You might want to install the \`Automake' and \`Perl' packages. Grab them from any GNU archive site." touch aclocal.m4 ;; autoconf) echo 1>&2 "\ WARNING: \`$1' is missing on your system. You should only need it if you modified \`configure.in'. You might want to install the \`Autoconf' and \`GNU m4' packages. Grab them from any GNU archive site." touch configure ;; autoheader) echo 1>&2 "\ WARNING: \`$1' is missing on your system. You should only need it if you modified \`acconfig.h' or \`configure.in'. You might want to install the \`Autoconf' and \`GNU m4' packages. Grab them from any GNU archive site." files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER([^):]*:\([^)]*\)).*/\1/p' configure.in` if test -z "$files"; then files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^):]*\)).*/\1/p' configure.in` test -z "$files" || files="$files.in" else files=`echo "$files" | sed -e 's/:/ /g'` fi test -z "$files" && files="config.h.in" touch $files ;; automake) echo 1>&2 "\ WARNING: \`$1' is missing on your system. You should only need it if you modified \`Makefile.am', \`acinclude.m4' or \`configure.in'. You might want to install the \`Automake' and \`Perl' packages. Grab them from any GNU archive site." find . -type f -name Makefile.am -print \ | sed 's/^\(.*\).am$/touch \1.in/' \ | sh ;; bison|yacc) echo 1>&2 "\ WARNING: \`$1' is missing on your system. You should only need it if you modified a \`.y' file. You may need the \`Bison' package in order for those modifications to take effect. You can get \`Bison' from any GNU archive site." rm -f y.tab.c y.tab.h if [ $# -ne 1 ]; then eval LASTARG="\${$#}" case "$LASTARG" in *.y) SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` if [ -f "$SRCFILE" ]; then cp "$SRCFILE" y.tab.c fi SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` if [ -f "$SRCFILE" ]; then cp "$SRCFILE" y.tab.h fi ;; esac fi if [ ! -f y.tab.h ]; then echo >y.tab.h fi if [ ! -f y.tab.c ]; then echo 'main() { return 0; }' >y.tab.c fi ;; lex|flex) echo 1>&2 "\ WARNING: \`$1' is missing on your system. You should only need it if you modified a \`.l' file. You may need the \`Flex' package in order for those modifications to take effect. You can get \`Flex' from any GNU archive site." rm -f lex.yy.c if [ $# -ne 1 ]; then eval LASTARG="\${$#}" case "$LASTARG" in *.l) SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` if [ -f "$SRCFILE" ]; then cp "$SRCFILE" lex.yy.c fi ;; esac fi if [ ! -f lex.yy.c ]; then echo 'main() { return 0; }' >lex.yy.c fi ;; makeinfo) echo 1>&2 "\ WARNING: \`$1' is missing on your system. You should only need it if you modified a \`.texi' or \`.texinfo' file, or any other file indirectly affecting the aspect of the manual. The spurious call might also be the consequence of using a buggy \`make' (AIX, DU, IRIX). You might want to install the \`Texinfo' package or the \`GNU make' package. Grab either from any GNU archive site." file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'` if test -z "$file"; then file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file` fi touch $file ;; *) echo 1>&2 "\ WARNING: \`$1' is needed, and you do not seem to have it handy on your system. You might have modified some files without having the proper tools for further handling them. Check the \`README' file, it often tells you about the needed prerequirements for installing this package. You may also peek at any GNU archive site, in case some other package would contain this missing \`$1' program." exit 1 ;; esac exit 0 --- NEW FILE: Makefile.in --- # # Simple Makefile for the support programs. # # documentation support: man2html # testing support: printenv recho zecho # # bashbug lives here but is created by the top-level makefile # # Currently only man2html is built # # # Copyright (C) 1998 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. # # Boilerplate # topdir = @top_srcdir@ srcdir = @srcdir@ VPATH = .:@srcdir@ BUILD_DIR = @BUILD_DIR@ RM = rm -f SHELL = @MAKE_SHELL@ CC = @CC@ EXEEXT = @EXEEXT@ # # Compiler options: # PROFILE_FLAGS = @PROFILE_FLAGS@ CFLAGS = @CFLAGS@ CFLAGS_FOR_BUILD = @CFLAGS_FOR_BUILD@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_FOR_BUILD = @CPPFLAGS_FOR_BUILD@ LOCAL_CFLAGS = @LOCAL_CFLAGS@ DEFS = @DEFS@ LOCAL_DEFS = @LOCAL_DEFS@ LOCAL_LDFLAGS = @LOCAL_LDFLAGS@ LIBS = @LIBS@ LDFLAGS = @LDFLAGS@ $(LOCAL_LDFLAGS) $(CFLAGS) LDFLAGS_FOR_BUILD = $(LDFLAGS) INCLUDES = -I${BUILD_DIR} -I${topdir} BASE_CCFLAGS = ${PROFILE_FLAGS} $(DEFS) $(LOCAL_DEFS) $(SYSTEM_FLAGS) \ ${INCLUDES} $(LOCAL_CFLAGS) CCFLAGS = $(BASE_CCFLAGS) $(CPPFLAGS) $(CFLAGS) CCFLAGS_FOR_BUILD = $(BASE_CCFLAGS) $(CPPFLAGS_FOR_BUILD) $(CFLAGS_FOR_BUILD) SRC1 = man2html.c OBJ1 = man2html.o .c.o: $(RM) $@ $(CC_FOR_BUILD) -c $(CCFLAGS_FOR_BUILD) $< all: man2html$(EXEEXT) man2html$(EXEEXT): $(OBJ1) $(CC) $(CCFLAGS) $(OBJ1) -o $@ ${LIBS} clean: rm man2html man2html.o: man2html.c --- NEW FILE: bashversion.c --- /* bashversion.c -- Display bash version information. */ /* Copyright (C) 2001 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include "config.h" #include "stdc.h" #include <stdio.h> #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #include "bashansi.h" #include "version.h" #include "conftypes.h" #define RFLAG 0x0001 #define VFLAG 0x0002 #define MFLAG 0x0004 #define PFLAG 0x0008 #define SFLAG 0x0010 #define LFLAG 0x0020 #define XFLAG 0x0040 extern int optind; extern char *optarg; extern char *dist_version; extern int patch_level; char *shell_name = "bash"; char *progname; static void usage() { fprintf(stderr, "%s: usage: %s [-hrvpmlsx]\n", progname, progname); } int main (argc, argv) int argc; char **argv; { int opt, oflags; char dv[128], *rv; if (progname = strrchr (argv[0], '/')) progname++; else progname = argv[0]; oflags = 0; while ((opt = getopt(argc, argv, "hrvmpslx")) != EOF) { switch (opt) { case 'h': usage (); exit (0); case 'r': oflags |= RFLAG; /* release */ break; case 'v': oflags |= VFLAG; /* version */ break; case 'm': oflags |= MFLAG; /* machtype */ break; case 'p': oflags |= PFLAG; /* patchlevel */ break; case 's': /* short version string */ oflags |= SFLAG; break; case 'l': /* long version string */ oflags |= LFLAG; break; case 'x': /* extended version information */ oflags |= XFLAG; break; default: usage (); exit (2); } } argc -= optind; argv += optind; if (argc > 0) { usage (); exit (2); } /* default behavior */ if (oflags == 0) oflags = SFLAG; if (oflags & (RFLAG|VFLAG)) { strcpy (dv, dist_version); rv = strchr (dv, '.'); if (rv) *rv++ = '\0'; else rv = "00"; } if (oflags & RFLAG) printf ("%s\n", dv); else if (oflags & VFLAG) printf ("%s\n", rv); else if (oflags & MFLAG) printf ("%s\n", MACHTYPE); else if (oflags & PFLAG) printf ("%d\n", patch_level); else if (oflags & SFLAG) printf ("%s\n", shell_version_string ()); else if (oflags & LFLAG) show_shell_version (0); else if (oflags & XFLAG) show_shell_version (1); exit (0); } --- NEW FILE: mkconffiles --- #! /bin/sh # # mkconffiles - create _distribution and _patchlevel files in preparation # for recreating `configure' from `configure.in' # # options: # -s srcdir directory where `configure' resides (defaults to `.') # -d outdir directory where the files should be written (defaults # to "$srcdir") # -v verbose # -n nocreate - don't create the output files # # Chet Ramey # ch...@po... # Copyright (C) 1996-2002 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. PROG=`basename $0` # defaults srcdir=. distname="_distribution" patchname="_patchlevel" while [ $# -gt 0 ]; do case "$1" in -s) shift; srcdir="$1"; shift;; -d) shift; outdir="$1"; shift;; -v) shift; verbose=yes ;; -n) shift; nocreate=yes;; --) shift; break;; *) echo "${PROG}: usage: ${PROG} [-s srcdir] [-d outdir] [-nv]" >&2; exit 2;; esac done if [ ! -f ${srcdir}/configure ]; then echo "${PROG}: ${srcdir}/configure not found" >&2 exit 1 fi # default output directory to source directory if [ -z "$outdir" ]; then outdir=${srcdir} fi DISTRIB=`grep '^BASHVERS' ${srcdir}/configure | sed 's:.*=::'` PATCH=`grep '^BASHPATCH' ${srcdir}/configure | sed 's:.*=::'` if [ -n "$verbose" ]; then echo "${PROG}: creating new distribution files for bash-${DISTRIB}.${PATCH} in ${outdir}" fi distout=${outdir}/${distname} patchout=${outdir}/${patchname} if [ -z "$nocreate" ]; then echo "$DISTRIB" > $distout echo "$PATCH" > $patchout fi if [ -n "$verbose" ]; then echo "${PROG}: created $distout and $patchout" fi exit 0 --- NEW FILE: bashbug.sh --- #!/bin/sh - # # bashbug - create a bug report and mail it to the bug address # # The bug address depends on the release status of the shell. Versions # with status `devel', `alpha', `beta', or `rc' mail bug reports to # ch...@po... and, optionally, to bas...@po.... # Other versions send mail to bug...@gn.... # # Copyright (C) 1996-2002 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. # # configuration section: # these variables are filled in by the make target in Makefile # MACHINE="!MACHINE!" OS="!OS!" CC="!CC!" CFLAGS="!CFLAGS!" RELEASE="!RELEASE!" PATCHLEVEL="!PATCHLEVEL!" RELSTATUS="!RELSTATUS!" MACHTYPE="!MACHTYPE!" PATH=/bin:/usr/bin:/usr/local/bin:$PATH export PATH # If the OS supplies a program to make temp files with semi-random names, # use it. : ${TMPDIR:=/tmp} rm_tmp1=false rm_tmp2=false # if we don't have mktemp or tempfile, we don't want to see error messages # like `mktemp: not found', so temporarily redirect stderr using {...} while # trying to run them. this may fail using old versions of the bourne shell # that run {...} blocks with redirections in subshells; in that case we're # no worse off than previous versions { TEMPFILE1=`mktemp "$TMPDIR/bbug.XXXXXX" 2>/dev/null` ; } 2>/dev/null if [ -z "$TEMPFILE1" ]; then { TEMPFILE1=`tempfile --prefix bbug --mode 600 2>/dev/null`; } 2>/dev/null fi if [ -z "$TEMPFILE1" ]; then TEMPFILE1=$TMPDIR/bbug.$$ rm_tmp1=true fi { TEMPFILE2=`mktemp "$TMPDIR/bbug.XXXXXX" 2>/dev/null`; } 2>/dev/null if [ -z "$TEMPFILE2" ]; then { TEMPFILE2=`tempfile --prefix bbug --mode 600 2>/dev/null`; } 2>/dev/null fi if [ -z "$TEMPFILE2" ]; then TEMPFILE2="$TMPDIR/bbug.$$.x" rm_tmp2=true fi USAGE="Usage: $0 [--help] [--version] [bug-report-email-address]" VERSTR="GNU bashbug, version ${RELEASE}.${PATCHLEVEL}-${RELSTATUS}" do_help= do_version= while [ $# -gt 0 ]; do case "$1" in --help) shift ; do_help=y ;; --version) shift ; do_version=y ;; --) shift ; break ;; -*) echo "bashbug: ${1}: invalid option" >&2 echo "$USAGE" >& 2 exit 2 ;; *) break ;; esac done if [ -n "$do_version" ]; then echo "${VERSTR}" exit 0 fi if [ -n "$do_help" ]; then echo "${VERSTR}" echo "${USAGE}" echo cat << HERE_EOF Bashbug is used to send mail to the Bash maintainers for when Bash doesn't behave like you'd like, or expect. Bashbug will start up your editor (as defined by the shell's EDITOR environment variable) with a preformatted bug report template for you to fill in. The report will be mailed to the bash maintainers by default. See the manual for details. If you invoke bashbug by accident, just quit your editor without saving any changes to the template, and no bug report will be sent. HERE_EOF exit 0 fi # Figure out how to echo a string without a trailing newline N=`echo 'hi there\c'` case "$N" in *c) n=-n c= ;; *) n= c='\c' ;; esac BASHTESTERS="bas...@po..." case "$RELSTATUS" in alpha*|beta*|devel*|rc*) BUG...@po... ;; *) BUG...@gn... ;; esac case "$RELSTATUS" in alpha*|beta*|devel*|rc*) echo "$0: This is a testing release. Would you like your bug report" echo "$0: to be sent to the bash-testers mailing list?" echo $n "$0: Send to bash-testers? $c" read ans case "$ans" in y*|Y*) BUGBASH="${BUGBASH},${BASHTESTERS}" ;; esac ;; esac BUGADDR="${1-$BUGBASH}" if [ -z "$DEFEDITOR" ] && [ -z "$EDITOR" ]; then if [ -x /usr/bin/editor ]; then DEFEDITOR=editor elif [ -x /usr/local/bin/ce ]; then DEFEDITOR=ce elif [ -x /usr/local/bin/emacs ]; then DEFEDITOR=emacs elif [ -x /usr/contrib/bin/emacs ]; then DEFEDITOR=emacs elif [ -x /usr/bin/emacs ]; then DEFEDITOR=emacs elif [ -x /usr/bin/xemacs ]; then DEFEDITOR=xemacs elif [ -x /usr/contrib/bin/jove ]; then DEFEDITOR=jove elif [ -x /usr/local/bin/jove ]; then DEFEDITOR=jove elif [ -x /usr/bin/vi ]; then DEFEDITOR=vi else echo "$0: No default editor found: attempting to use vi" >&2 DEFEDITOR=vi fi fi : ${EDITOR=$DEFEDITOR} : ${USER=${LOGNAME-`whoami`}} trap 'rm -f "$TEMPFILE1" "$TEMPFILE2"; exit 1' 1 2 3 13 15 trap 'rm -f "$TEMPFILE1" "$TEMPFILE2"' 0 UN= if (uname) >/dev/null 2>&1; then UN=`uname -a` fi if [ -f /usr/lib/sendmail ] ; then RMAIL="/usr/lib/sendmail" SMARGS="-i -t" elif [ -f /usr/sbin/sendmail ] ; then RMAIL="/usr/sbin/sendmail" SMARGS="-i -t" else RMAIL=rmail SMARGS="$BUGADDR" fi INITIAL_SUBJECT='[50 character or so descriptive subject here (for reference)]' # this is raceable unless (hopefully) we used mktemp(1) or tempfile(1) $rm_tmp1 && rm -f "$TEMPFILE1" cat > "$TEMPFILE1" <<EOF From: ${USER} To: ${BUGADDR} Subject: ${INITIAL_SUBJECT} Configuration Information [Automatically generated, do not change]: Machine: $MACHINE OS: $OS Compiler: $CC Compilation CFLAGS: $CFLAGS uname output: $UN Machine Type: $MACHTYPE Bash Version: $RELEASE Patch Level: $PATCHLEVEL Release Status: $RELSTATUS Description: [Detailed description of the problem, suggestion, or complaint.] Repeat-By: [Describe the sequence of events that causes the problem to occur.] Fix: [Description of how to fix the problem. If you don't know a fix for the problem, don't include this section.] EOF # this is still raceable unless (hopefully) we used mktemp(1) or tempfile(1) $rm_tmp2 && rm -f "$TEMPFILE2" cp "$TEMPFILE1" "$TEMPFILE2" chmod u+w "$TEMPFILE1" trap '' 2 # ignore interrupts while in editor edstat=1 while [ $edstat -ne 0 ]; do $EDITOR "$TEMPFILE1" edstat=$? if [ $edstat -ne 0 ]; then echo "$0: editor \`$EDITOR' exited with nonzero status." echo "$0: Perhaps it was interrupted." echo "$0: Type \`y' to give up, and lose your bug report;" echo "$0: type \`n' to re-enter the editor." echo $n "$0: Do you want to give up? $c" read ans case "$ans" in [Yy]*) exit 1 ;; esac continue fi # find the subject from the temp file and see if it's been changed CURR_SUB=`grep '^Subject: ' "$TEMPFILE1" | sed 's|^Subject:[ ]*||' | sed 1q` case "$CURR_SUB" in "${INITIAL_SUBJECT}") echo echo "$0: You have not changed the subject from the default." echo "$0: Please use a more descriptive subject header." echo "$0: Type \`y' to give up, and lose your bug report;" echo "$0: type \`n' to re-enter the editor." echo $n "$0: Do you want to give up? $c" read ans case "$ans" in [Yy]*) exit 1 ;; esac echo "$0: The editor will be restarted in five seconds." sleep 5 edstat=1 ;; esac done trap 'rm -f "$TEMPFILE1" "$TEMPFILE2"; exit 1' 2 # restore trap on SIGINT if cmp -s "$TEMPFILE1" "$TEMPFILE2" then echo "File not changed, no bug report submitted." exit fi echo $n "Send bug report? [y/n] $c" read ans case "$ans" in [Nn]*) exit 0 ;; esac ${RMAIL} $SMARGS < "$TEMPFILE1" || { cat "$TEMPFILE1" >> $HOME/dead.bashbug echo "$0: mail failed: report saved in $HOME/dead.bashbug" >&2 } exit 0 --- NEW FILE: printenv.sh --- #! /bin/sh - # Copyright (C) 1996-2002 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. if [ $# -eq 0 ]; then env exit elif eval [ "\${$1-unset}" = "unset" ]; then exit 1 else eval echo \$$1 exit 0 fi --- NEW FILE: texi2dvi --- #! /bin/sh # texi2dvi --- produce DVI (or PDF) files from Texinfo (or LaTeX) sources. # $Id: texi2dvi,v 1.1 2005/05/22 10:13:25 earnie Exp $ # # Copyright (C) 1992, 93, 94, 95, 96, 97, 98, 99 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, you can either send email to this # program's maintainer or write to: The Free Software Foundation, # Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA. # # Original author: Noah Friedman <fri...@gn...>. # # Please send bug reports, etc. to bug...@gn.... # If possible, please send a copy of the output of the script called with # the `--debug' option when making a bug report. # This string is expanded by rcs automatically when this file is checked out. rcs_revision='$Revision: 1.1 $' rcs_version=`set - $rcs_revision; echo $2` program=`echo $0 | sed -e 's!.*/!!'` version="texi2dvi (GNU Texinfo 4.0) $rcs_version Copyright (C) 1999 Free Software Foundation, Inc. There is NO warranty. You may redistribute this software under the terms of the GNU General Public License. For more information about these matters, see the files named COPYING." usage="Usage: $program [OPTION]... FILE... Run each Texinfo or LaTeX FILE through TeX in turn until all cross-references are resolved, building all indices. The directory containing each FILE is searched for included files. The suffix of FILE is used to determine its language (LaTeX or Texinfo). Makeinfo is used to perform Texinfo macro expansion before running TeX when needed. Options: -@ Use @input instead of \input; for preloaded Texinfo. -b, --batch No interaction. -c, --clean Remove all auxiliary files. -D, --debug Turn on shell debugging (set -x). -e, --expand Force macro expansion using makeinfo. -I DIR Search DIR for Texinfo files. -h, --help Display this help and exit successfully. -l, --language=LANG Specify the LANG of FILE: LaTeX or Texinfo. -p, --pdf Use pdftex or pdflatex for processing. -q, --quiet No output unless errors (implies --batch). -s, --silent Same as --quiet. -t, --texinfo=CMD Insert CMD after @setfilename in copy of input file. Multiple values accumulate. -v, --version Display version information and exit successfully. -V, --verbose Report on what is done. The values of the BIBTEX, LATEX (or PDFLATEX), MAKEINDEX, MAKEINFO, TEX (or PDFTEX), and TEXINDEX environment variables are used to run those commands, if they are set. Email bug reports to <bug...@gn...>, general questions and discussion to <hel...@gn...>." # Initialize variables for option overriding and otherwise. # Don't use `unset' since old bourne shells don't have this command. # Instead, assign them an empty value. escape='\' batch=false # eval for batch mode clean= debug= expand= # t for expansion via makeinfo oformat=dvi set_language= miincludes= # makeinfo include path textra= tmpdir=${TMPDIR:-/tmp}/t2d$$ # avoid collisions on 8.3 filesystems. txincludes= # TEXINPUTS extensions txiprereq=19990129 # minimum texinfo.tex version to have macro expansion quiet= # by default let the tools' message be displayed verbose=false # echo for verbose mode orig_pwd=`pwd` # Systems which define $COMSPEC or $ComSpec use semicolons to separate # directories in TEXINPUTS. if test -n "$COMSPEC$ComSpec"; then path_sep=";" else path_sep=":" fi # Save this so we can construct a new TEXINPUTS path for each file. TEXINPUTS_orig="$TEXINPUTS" # Unfortunately makeindex does not read TEXINPUTS. INDEXSTYLE_orig="$INDEXSTYLE" export TEXINPUTS INDEXSTYLE # Push a token among the arguments that will be used to notice when we # ended options/arguments parsing. # Use "set dummy ...; shift" rather than 'set - ..." because on # Solaris set - turns off set -x (but keeps set -e). # Use ${1+"$@"} rather than "$@" because Digital Unix and Ultrix 4.3 # still expand "$@" to a single argument (the empty string) rather # than nothing at all. arg_sep="$$--$$" set dummy ${1+"$@"} "$arg_sep"; shift # # Parse command line arguments. while test x"$1" != x"$arg_sep"; do # Handle --option=value by splitting apart and putting back on argv. case "$1" in --*=*) opt=`echo "$1" | sed -e 's/=.*//'` val=`echo "$1" | sed -e 's/[^=]*=//'` shift set dummy "$opt" "$val" ${1+"$@"}; shift ;; esac # This recognizes --quark as --quiet. So what. case "$1" in -@ ) escape=@;; # Silently and without documentation accept -b and --b[atch] as synonyms. -b | --b*) batch=eval;; -q | -s | --q* | --s*) quiet=t; batch=eval;; -c | --c*) clean=t;; -D | --d*) debug=t;; -e | --e*) expand=t;; -h | --h*) echo "$usage"; exit 0;; -I | --I*) shift miincludes="$miincludes -I $1" txincludes="$txincludes$path_sep$1" ;; -l | --l*) shift; set_language=$1;; -p | --p*) oformat=pdf;; -t | --t*) shift; textra="$textra\\ $1";; -v | --vers*) echo "$version"; exit 0;; -V | --verb*) verbose=echo;; --) # What remains are not options. shift while test x"$1" != x"$arg_sep"; do set dummy ${1+"$@"} "$1"; shift shift done break;; -*) echo "$0: Unknown or ambiguous option \`$1'." >&2 echo "$0: Try \`--help' for more information." >&2 exit 1;; *) set dummy ${1+"$@"} "$1"; shift;; esac shift done # Pop the token shift # Interpret remaining command line args as filenames. if test $# = 0; then echo "$0: Missing file arguments." >&2 echo "$0: Try \`--help' for more information." >&2 exit 2 fi # Prepare the temporary directory. Remove it at exit, unless debugging. if test -z "$debug"; then trap "cd / && rm -rf $tmpdir" 0 1 2 15 fi # Create the temporary directory with strict rights (umask 077 && mkdir $tmpdir) || exit 1 # Prepare the tools we might need. This may be extra work in some # cases, but improves the readibility of the script. utildir=$tmpdir/utils mkdir $utildir || exit 1 # A sed script that preprocesses Texinfo sources in order to keep the # iftex sections only. We want to remove non TeX sections, and # comment (with `@c texi2dvi') TeX sections so that makeinfo does not # try to parse them. Nevertheless, while commenting TeX sections, # don't comment @macro/@end macro so that makeinfo does propagate # them. Unfortunately makeinfo --iftex --no-ifhtml --no-ifinfo # doesn't work well enough (yet) to use that, so work around with sed. comment_iftex_sed=$utildir/comment.sed cat <<EOF >$comment_iftex_sed /^@tex/,/^@end tex/{ s/^/@c texi2dvi/ } /^@iftex/,/^@end iftex/{ s/^/@c texi2dvi/ /^@c texi2dvi@macro/,/^@c texi2dvi@end macro/{ s/^@c texi2dvi// } } /^@html/,/^@end html/d /^@ifhtml/,/^@end ifhtml/d /^@ifnottex/,/^@end ifnottex/d /^@ifinfo/,/^@end ifinfo/{ /^@node/p /^@menu/,/^@end menu/p d } EOF # Uncommenting is simple: Remove any leading `@c texi2dvi'. uncomment_iftex_sed=$utildir/uncomment.sed cat <<EOF >$uncomment_iftex_sed s/^@c texi2dvi// EOF # A shell script that computes the list of xref files. # Takes the filename (without extension) of which we look for xref # files as argument. The index files must be reported last. get_xref_files=$utildir/get_xref.sh cat <<\EOF >$get_xref_files #! /bin/sh # Get list of xref files (indexes, tables and lists). # Find all files having root filename with a two-letter extension, # saves the ones that are really Texinfo-related files. .?o? catches # LaTeX tables and lists. for this_file in "$1".?o? "$1".aux "$1".?? "$1".idx; do # If file is empty, skip it. test -s "$this_file" || continue # If the file is not suitable to be an index or xref file, don't # process it. The file can't be if its first character is not a # backslash or single quote. first_character=`sed -n '1s/^\(.\).*$/\1/p;q' $this_file` if test "x$first_character" = "x\\" \ || test "x$first_character" = "x'"; then xref_files="$xref_files ./$this_file" fi done echo "$xref_files" EOF chmod 500 $get_xref_files # File descriptor usage: # 0 standard input # 1 standard output (--verbose messages) # 2 standard error # 3 some systems may open it to /dev/tty # 4 used on the Kubota Titan # 5 tools output (turned off by --quiet) # Tools' output. If quiet, discard, else redirect to the message flow. if test "$quiet" = t; then exec 5>/dev/null else exec 5>&1 fi # Enable tracing test "$debug" = t && set -x # # TeXify files. for command_line_filename in ${1+"$@"}; do $verbose "Processing $command_line_filename ..." # If the COMMAND_LINE_FILENAME is not absolute (e.g., --debug.tex), # prepend `./' in order to avoid that the tools take it as an option. echo "$command_line_filename" | egrep '^(/|[A-z]:/)' >/dev/null \ || command_line_filename="./$command_line_filename" # See if the file exists. If it doesn't we're in trouble since, even # though the user may be able to reenter a valid filename at the tex # prompt (assuming they're attending the terminal), this script won't # be able to find the right xref files and so forth. if test ! -r "$command_line_filename"; then echo "$0: Could not read $command_line_filename, skipping." >&2 continue fi # Get the name of the current directory. We want the full path # because in clean mode we are in tmp, in which case a relative # path has no meaning. filename_dir=`echo $command_line_filename | sed 's!/[^/]*$!!;s!^$!.!'` filename_dir=`cd "$filename_dir" >/dev/null && pwd` # Strip directory part but leave extension. filename_ext=`basename "$command_line_filename"` # Strip extension. filename_noext=`echo "$filename_ext" | sed 's/\.[^.]*$//'` ext=`echo "$filename_ext" | sed 's/^.*\.//'` # _src. Use same basename since we want to generate aux files with # the same basename as the manual. If --expand, then output the # macro-expanded file to here, else copy the original file. tmpdir_src=$tmpdir/src filename_src=$tmpdir_src/$filename_noext.$ext # _xtr. The file with the user's extra commands. tmpdir_xtr=$tmpdir/xtr filename_xtr=$tmpdir_xtr/$filename_noext.$ext # _bak. Copies of the previous xref files (another round is run if # they differ from the new one). tmpdir_bak=$tmpdir/bak # Make all those directories and give up if we can't succeed. mkdir $tmpdir_src $tmpdir_xtr $tmpdir_bak || exit 1 # Source file might include additional sources. Put `.' and # directory where source file(s) reside in TEXINPUTS before anything # else. `.' goes first to ensure that any old .aux, .cps, # etc. files in ${directory} don't get used in preference to fresher # files in `.'. Include orig_pwd in case we are in clean mode, where # we've cd'd to a temp directory. common=".$path_sep$orig_pwd$path_sep$filename_dir$path_sep$txincludes$path_sep" TEXINPUTS="$common$TEXINPUTS_orig" INDEXSTYLE="$common$INDEXSTYLE_orig" # If the user explicitly specified the language, use that. # Otherwise, if the first line is \input texinfo, assume it's texinfo. # Otherwise, guess from the file extension. if test -n "$set_language"; then language=$set_language elif sed 1q "$command_line_filename" | fgrep 'input texinfo' >/dev/null; then language=texinfo else language= fi # Get the type of the file (latex or texinfo) from the given language # we just guessed, or from the file extension if not set yet. case ${language:-$filename_ext} in [lL]a[tT]e[xX] | *.ltx | *.tex) # Assume a LaTeX file. LaTeX needs bibtex and uses latex for # compilation. No makeinfo. bibtex=${BIBTEX:-bibtex} makeinfo= # no point in running makeinfo on latex source. texindex=${MAKEINDEX:-makeindex} if test $oformat = dvi; then tex=${LATEX:-latex} else tex=${PDFLATEX:-pdflatex} fi ;; *) # Assume a Texinfo file. Texinfo files need makeinfo, texindex and tex. bibtex= texindex=${TEXINDEX:-texindex} if test $oformat = dvi; then tex=${TEX:-tex} else tex=${PDFTEX:-pdftex} fi # Unless required by the user, makeinfo expansion is wanted only # if texinfo.tex is too old. if test "$expand" = t; then makeinfo=${MAKEINFO:-makeinfo} else # Check if texinfo.tex performs macro expansion by looking for # its version. The version is a date of the form YEAR-MO-DA. # We don't need to use [0-9] to match the digits since anyway # the comparison with $txiprereq, a number, will fail with non # digits. txiversion_tex=txiversion.tex echo '\input texinfo.tex @bye' >$tmpdir/$txiversion_tex # Run in the tmpdir to avoid leaving files. eval `cd $tmpdir >/dev/null \ && $tex $txiversion_tex 2>/dev/null \ | sed -n 's/^.*\[\(.*\)version \(....\)-\(..\)-\(..\).*$/txiformat=\1 txiversion="\2\3\4"/p'` $verbose "texinfo.tex preloaded as \`$txiformat', version is \`$txiversion' ..." if test "$txiprereq" -le "$txiversion" >/dev/null 2>&1; then makeinfo= else makeinfo=${MAKEINFO:-makeinfo} fi # As long as we had to run TeX, offer the user this convenience if test "$txiformat" = Texinfo; then escape=@ fi fi ;; esac # Expand macro commands in the original source file using Makeinfo. # Always use `end' footnote style, since the `separate' style # generates different output (arguably this is a bug in -E). # Discard main info output, the user asked to run TeX, not makeinfo. if test -n "$makeinfo"; then $verbose "Macro-expanding $command_line_filename to $filename_src ..." sed -f $comment_iftex_sed "$command_line_filename" \ | $makeinfo --footnote-style=end -I "$filename_dir" $miincludes \ -o /dev/null --macro-expand=- \ | sed -f $uncomment_iftex_sed >"$filename_src" filename_input=$filename_src fi # If makeinfo failed (or was not even run), use the original file as input. if test $? -ne 0 \ || test ! -r "$filename_src"; then $verbose "Reverting to $command_line_filename ..." filename_input=$filename_dir/$filename_ext fi # Used most commonly for @finalout, @smallbook, etc. if test -n "$textra"; then $verbose "Inserting extra commands: $textra" sed '/^@setfilename/a\ '"$textra" "$filename_input" >$filename_xtr filename_input=$filename_xtr fi # If clean mode was specified, then move to the temporary directory. if test "$clean" = t; then $verbose "cd $tmpdir_src" cd "$tmpdir_src" || exit 1 fi while :; do # will break out of loop below orig_xref_files=`$get_xref_files "$filename_noext"` # Save copies of originals for later comparison. if test -n "$orig_xref_files"; then $verbose "Backing up xref files: `echo $orig_xref_files | sed 's|\./||g'`" cp $orig_xref_files $tmpdir_bak fi # Run bibtex on current file. # - If its input (AUX) exists. # - If AUX contains both `\bibdata' and `\bibstyle'. # - If some citations are missing (LOG contains `Citation'). # or the LOG complains of a missing .bbl # # We run bibtex first, because I can see reasons for the indexes # to change after bibtex is run, but I see no reason for the # converse. # # Don't try to be too smart. Running bibtex only if the bbl file # exists and is older than the LaTeX file is wrong, since the # document might include files that have changed. Because there # can be several AUX (if there are \include's), but a single LOG, # looking for missing citations in LOG is easier, though we take # the risk to match false messages. if test -n "$bibtex" \ && test -r "$filename_noext.aux" \ && test -r "$filename_noext.log" \ && (grep '^\\bibdata[{]' "$filename_noext.aux" \ && grep '^\\bibstyle[{]' "$filename_noext.aux" \ && (grep 'Warning:.*Citation.*undefined' "$filename_noext.log" \ || grep 'No file .*\.bbl\.' "$filename_noext.log")) \ >/dev/null 2>&1; \ then $verbose "Running $bibtex $filename_noext ..." if $bibtex "$filename_noext" >&5; then :; else echo "$0: $bibtex exited with bad status, quitting." >&2 exit 1 fi fi # What we'll run texindex on -- exclude non-index files. # Since we know index files are last, it is correct to remove everything # before .aux and .?o?. index_files=`echo "$orig_xref_files" \ | sed "s!.*\.aux!!g; s!./$filename_noext\..o.!!g; s/^[ ]*//;s/[ ]*$//"` # Run texindex (or makeindex) on current index files. If they # already exist, and after running TeX a first time the index # files don't change, then there's no reason to run TeX again. # But we won't know that if the index files are out of date or # nonexistent. if test -n "$texindex" && test -n "$index_files"; then $verbose "Running $texindex $index_files ..." if $texindex $index_files 2>&5 1>&2; then :; else echo "$0: $texindex exited with bad status, quitting." >&2 exit 1 fi fi # Finally, run TeX. # Prevent $ESCAPE from being interpreted by the shell if it happens # to be `/'. $batch tex_args="\\${escape}nonstopmode\ \\${escape}input" $verbose "Running $cmd ..." cmd="$tex $tex_args $filename_input" if $cmd >&5; then :; else echo "$0: $tex exited with bad status, quitting." >&2 echo "$0: see $filename_noext.log for errors." >&2 test "$clean" = t \ && cp "$filename_noext.log" "$orig_pwd" exit 1 fi # Decide if looping again is needed. finished=t # LaTeX (and the package changebar) report in the LOG file if it # should be rerun. This is needed for files included from # subdirs, since texi2dvi does not try to compare xref files in # subdirs. Performing xref files test is still good since LaTeX # does not report changes in xref files. if fgrep "Rerun to get" "$filename_noext.log" >/dev/null 2>&1; then finished= fi # Check if xref files changed. new_xref_files=`$get_xref_files "$filename_noext"` $verbose "Original xref files = `echo $orig_xref_files | sed 's|\./||g'`" $verbose "New xref files = `echo $new_xref_files | sed 's|\./||g'`" # If old and new lists don't at least have the same file list, # then one file or another has definitely changed. test "x$orig_xref_files" != "x$new_xref_files" && finished= # File list is the same. We must compare each file until we find # a difference. if test -n "$finished"; then for this_file in $new_xref_files; do $verbose "Comparing xref file `echo $this_file | sed 's|\./||g'` ..." # cmp -s returns nonzero exit status if files differ. if cmp -s "$this_file" "$tmpdir_bak/$this_file"; then :; else # We only need to keep comparing until we find one that # differs, because we'll have to run texindex & tex again no # matter how many more there might be. finished= $verbose "xref file `echo $this_file | sed 's|\./||g'` differed ..." test "$debug" = t && diff -c "$tmpdir_bak/$this_file" "$this_file" break fi done fi # If finished, exit the loop, else rerun the loop. test -n "$finished" && break done # If we were in clean mode, compilation was in a tmp directory. # Copy the DVI (or PDF) file into the directory where the compilation # has been done. (The temp dir is about to get removed anyway.) # We also return to the original directory so that # - the next file is processed in correct conditions # - the temporary file can be removed if test -n "$clean"; then $verbose "Copying $oformat file from `pwd` to $orig_pwd" cp -p "./$filename_noext.$oformat" "$orig_pwd" cd / # in case $orig_pwd is on a different drive (for DOS) cd $orig_pwd || exit 1 fi # Remove temporary files. if test "x$debug" = "x"; then $verbose "Removing $tmpdir_src $tmpdir_xtr $tmpdir_bak ..." cd / rm -rf $tmpdir_src $tmpdir_xtr $tmpdir_bak fi done $verbose "$0 done." exit 0 # exit successfully, not however we ended the loop. --- NEW FILE: printenv.c --- /* printenv -- minimal clone of BSD printenv(1). usage: printenv [varname] Chet Ramey ch...@po... */ /* Copyright (C) 1997-2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ extern char **environ; int main (argc, argv) int argc; char **argv; { register char **envp, *eval; int len; argv++; argc--; /* printenv */ if (argc == 0) { for (envp = environ; *envp; envp++) puts (*envp); exit (0); } /* printenv varname */ len = strlen (*argv); for (envp = environ; *envp; envp++) { if (**argv == **envp && strncmp (*envp, *argv, len) == 0) { eval = *envp + len; /* If the environment variable doesn't have an `=', ignore it. */ if (*eval == '=') { puts (eval + 1); exit (0); } } } exit (1); } --- NEW FILE: mksignames.c --- /* signames.c -- Create and write `signames.h', which contains an array of signal names. */ /* Copyright (C) 1992 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #include <stdio.h> #include <sys/types.h> #include <signal.h> #if defined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif /* HAVE_STDLIB_H */ #if !defined (NSIG) # define NSIG 64 #endif /* * Special traps: * EXIT == 0 * DEBUG == NSIG * ERR == NSIG+1 */ #define LASTSIG NSIG+1 char *signal_names[2 * NSIG + 3]; #define signal_names_size (sizeof(signal_names)/sizeof(signal_names[0])) char *progname; /* AIX 4.3 defines SIGRTMIN and SIGRTMAX as 888 and 999 respectively. I don't want to allocate so much unused space for the intervening signal numbers, so we just punt if SIGRTMAX is past the bounds of the signal_names array (handled in configure). */ #if defined (SIGRTMAX) && defined (UNUSABLE_RT_SIGNALS) # undef SIGRTMAX # undef SIGRTMIN #endif #if defined (SIGRTMAX) || defined (SIGRTMIN) # define RTLEN 14 # define RTLIM 256 #endif void initialize_signames () { register int i; #if defined (SIGRTMAX) || defined (SIGRTMIN) int rtmin, rtmax, rtcnt; #endif for (i = 1; i < signal_names_size; i++) signal_names[i] = (char *)NULL; /* `signal' 0 is what we do on exit. */ signal_names[0] = "EXIT"; /* Place signal names which can be aliases for more common signal names first. This allows (for example) SIGABRT to overwrite SIGLOST. */ /* POSIX 1003.1b-1993 real time signals, but take care of incomplete implementations. Acoording to the standard, both, SIGRTMIN and SIGRTMAX must be defined, SIGRTMIN must be stricly less than SIGRTMAX, and the difference must be at least 7, that is, there must be at least eight distinct real time signals. */ /* The generated signal names are SIGRTMIN, SIGRTMIN+1, ..., SIGRTMIN+x, SIGRTMAX-x, ..., SIGRTMAX-1, SIGRTMAX. If the number of RT signals is odd, there is an extra SIGRTMIN+(x+1). These names are the ones used by ksh and /usr/xpg4/bin/sh on SunOS5. */ #if defined (SIGRTMIN) rtmin = SIGRTMIN; signal_names[rtmin] = "SIGRTMIN"; #endif #if defined (SIGRTMAX) rtmax = SIGRTMAX; signal_names[rtmax] = "SIGRTMAX"; #endif #if defined (SIGRTMAX) && defined (SIGRTMIN) if (rtmax > rtmin) { rtcnt = (rtmax - rtmin - 1) / 2; /* croak if there are too many RT signals */ if (rtcnt >= RTLIM/2) { rtcnt = RTLIM/2-1; fprintf(stderr, "%s: error: more than %i real time signals, fix `%s'\n", progname, RTLIM, progname); } for (i = 1; i <= rtcnt; i++) { signal_names[rtmin+i] = (char *)malloc(RTLEN); if (signal_names[rtmin+i]) sprintf (signal_names[rtmin+i], "SIGRTMIN+%d", i); signal_names[rtmax-i] = (char *)malloc(RTLEN); if (signal_names[rtmax-i]) sprintf (signal_names[rtmax-i], "SIGRTMAX-%d", i); } if (rtcnt < RTLIM/2-1 && rtcnt != (rtmax-rtmin)/2) { /* Need an extra RTMIN signal */ signal_names[rtmin+rtcnt+1] = (char *)malloc(RTLEN); if (signal_names[rtmin+rtcnt+1]) sprintf (signal_names[rtmin+rtcnt+1], "SIGRTMIN+%d", rtcnt+1); } } #endif /* SIGRTMIN && SIGRTMAX */ /* AIX */ #if defined (SIGLOST) /* resource lost (eg, record-lock lost) */ signal_names[SIGLOST] = "SIGLOST"; #endif #if defined (SIGMSG) /* HFT input data pending */ signal_names[SIGMSG] = "SIGMSG"; #endif #if defined (SIGDANGER) /* system crash imminent */ signal_names[SIGDANGER] = "SIGDANGER"; #endif #if defined (SIGMIGRATE) /* migrate process to another CPU */ signal_names[SIGMIGRATE] = "SIGMIGRATE"; #endif #if defined (SIGPRE) /* programming error */ signal_names[SIGPRE] = "SIGPRE"; #endif #if defined (SIGVIRT) /* AIX virtual time alarm */ signal_names[SIGVIRT] = "SIGVIRT"; #endif #if defined (SIGALRM1) /* m:n condition variables */ signal_names[SIGALRM1] = "SIGALRM1"; #endif #if defined (SIGWAITING) /* m:n scheduling */ signal_names[SIGWAITING] = "SIGWAITING"; #endif #if defined (SIGGRANT) /* HFT monitor mode granted */ signal_names[SIGGRANT] = "SIGGRANT"; #endif #if defined (SIGKAP) /* keep alive poll from native keyboard */ signal_names[SIGKAP] = "SIGKAP"; #endif #if defined (SIGRETRACT) /* HFT monitor mode retracted */ signal_names[SIGRETRACT] = "SIGRETRACT"; #endif #if defined (SIGSOUND) /* HFT sound sequence has completed */ signal_names[SIGSOUND] = "SIGSOUND"; #endif #if defined (SIGSAK) /* Secure Attention Key */ signal_names[SIGSAK] = "SIGSAK"; #endif /* SunOS5 */ #if defined (SIGLWP) /* special signal used by thread library */ signal_names[SIGLWP] = "SIGLWP"; #endif #if defined (SIGFREEZE) /* special signal used by CPR */ signal_names[SIGFREEZE] = "SIGFREEZE"; #endif #if defined (SIGTHAW) /* special signal used by CPR */ signal_names[SIGTHAW] = "SIGTHAW"; #endif #if defined (SIGCANCEL) /* thread cancellation signal used by libthread */ signal_names[SIGCANCEL] = "SIGCANCEL"; #endif /* HP-UX */ #if defined (SIGDIL) /* DIL signal (?) */ signal_names[SIGDIL] = "SIGDIL"; #endif /* System V */ #if defined (SIGCLD) /* Like SIGCHLD. */ signal_names[SIGCLD] = "SIGCLD"; #endif #if defined (SIGPWR) /* power state indication */ signal_names[SIGPWR] = "SIGPWR"; #endif #if defined (SIGPOLL) /* Pollable event (for streams) */ signal_names[SIGPOLL] = "SIGPOLL"; #endif /* Unknown */ #if defined (SIGWINDOW) signal_names[SIGWINDOW] = "SIGWINDOW"; #endif /* Common */ #if defined (SIGHUP) /* hangup */ signal_names[SIGHUP] = "SIGHUP"; #endif #if defined (SIGINT) /* interrupt */ signal_names[SIGINT] = "SIGINT"; #endif #if defined (SIGQUIT) /* quit */ signal_names[SIGQUIT] = "SIGQUIT"; #endif #if defined (SIGILL) /* illegal instruction (not reset when caught) */ signal_names[SIGILL] = "SIGILL"; #endif #if defined (SIGTRAP) /* trace trap (not reset when caught) */ signal_names[SIGTRAP] = "SIGTRAP"; #endif #if defined (SIGIOT) /* IOT instruction */ signal_names[SIGIOT] = "SIGIOT"; #endif #if defined (SIGABRT) /* Cause current process to dump core. */ signal_names[SIGABRT] = "SIGABRT"; #endif #if defined (SIGEMT) /* EMT instruction */ signal_names[SIGEMT] = "SIGEMT"; #endif #if defined (SIGFPE) /* floating point exception */ signal_names[SIGFPE] = "SIGFPE"; #endif #if defined (SIGKILL) /* kill (cannot be caught or ignored) */ signal_names[SIGKILL] = "SIGKILL"; #endif #if defined (SIGBUS) /* bus error */ signal_names[SIGBUS] = "SIGBUS"; #endif #if defined (SIGSEGV) /* segmentation violation */ signal_names[SIGSEGV] = "SIGSEGV"; #endif #if defined (SIGSYS) /* bad argument to system call */ signal_names[SIGSYS] = "SIGSYS"; #endif #if defined (SIGPIPE) /* write on a pipe with no one to read it */ signal_names[SIGPIPE] = "SIGPIPE"; #endif #if defined (SIGALRM) /* alarm clock */ signal_names[SIGALRM] = "SIGALRM"; #endif #if defined (SIGTERM) /* software termination signal from kill */ signal_names[SIGTERM] = "SIGTERM"; #endif #if defined (SIGURG) /* urgent condition on IO channel */ signal_names[SIGURG] = "SIGURG"; #endif #if defined (SIGSTOP) /* sendable stop signal not from tty */ signal_names[SIGSTOP] = "SIGSTOP"; #endif #if defined (SIGTSTP) /* stop signal from tty */ signal_names[SIGTSTP] = "SIGTSTP"; #endif #if defined (SIGCONT) /* continue a stopped process */ signal_names[SIGCONT] = "SIGCONT"; #endif #if defined (SIGCHLD) /* to parent on child stop or exit */ signal_names[SIGCHLD] = "SIGCHLD"; #endif #if defined (SIGTTIN) /* to readers pgrp upon background tty read */ signal_names[SIGTTIN] = "SIGTTIN"; #endif #if defined (SIGTTOU) /* like TTIN for output if (tp->t_local<OSTOP) */ signal_names[SIGTTOU] = "SIGTTOU"; #endif #if defined (SIGIO) /* input/output possible signal */ signal_names[SIGIO] = "SIGIO"; #endif #if defined (SIGXCPU) /* exceeded CPU time limit */ signal_names[SIGXCPU] = "SIGXCPU"; #endif #if defined (SIGXFSZ) /* exceeded file size limit */ signal_names[SIGXFSZ] = "SIGXFSZ"; #endif #if defined (SIGVTALRM) /* virtual time alarm */ signal_names[SIGVTALRM] = "SIGVTALRM"; #endif #if defined (SIGPROF) /* profiling time alarm */ signal_names[SIGPROF] = "SIGPROF"; #endif #if defined (SIGWINCH) /* window changed */ signal_names[SIGWINCH] = "SIGWINCH"; #endif /* 4.4 BSD */ #if defined (SIGINFO) && !defined (_SEQUENT_) /* information request */ signal_names[SIGINFO] = "SIGINFO"; #endif #if defined (SIGUSR1) /* user defined signal 1 */ signal_names[SIGUSR1] = "SIGUSR1"; #endif #if defined (SIGUSR2) /* user defined signal 2 */ signal_names[SIGUSR2] = "SIGUSR2"; #endif #if defined (SIGKILLTHR) /* BeOS: Kill Thread */ signal_names[SIGKILLTHR] = "SIGKILLTHR"; #endif for (i = 0; i < NSIG; i++) if (signal_names[i] == (char *)NULL) { signal_names[i] = (char *)malloc (18); if (signal_names[i]) sprintf (signal_names[i], "SIGJUNK(%d)", i); } signal_names[NSIG] = "DEBUG"; signal_names[NSIG+1] = "ERR"; } void write_signames (stream) FILE *stream; { register int i; fprintf (stream, "/* This file was automatically created by %s.\n", progname); fprintf (stream, " Do not edit. Edit support/mksignames.c instead. */\n\n"); fprintf (stream, "/* A translation list so we can be polite to our users. */\n"); fprintf ... [truncated message content] |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:36
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/tilde In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/tilde Added Files: Makefile.in README shell.c tilde.c tilde.h Log Message: Pristine source --- NEW FILE: shell.c --- /* shell.c -- tilde utility functions that are normally provided by bash when readline is linked as part of the shell. */ /* Copyright (C) 1998 Free Software Foundation, Inc. This file is part of the GNU Tilde Library. The GNU Tilde Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Tilde Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if defined (HAVE_CONFIG_H) # include <config.h> #endif #if defined (HAVE_UNISTD_H) # ifdef _MINIX # include <sys/types.h> # endif # include <unistd.h> #endif /* HAVE_UNISTD_H */ #if defined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif /* HAVE_STDLIB_H */ #if defined (HAVE_STRING_H) # include <string.h> #else # include <strings.h> #endif /* !HAVE_STRING_H */ #include <pwd.h> #if !defined (HAVE_GETPW_DECLS) extern struct passwd *getpwuid (); #endif /* !HAVE_GETPW_DECLS */ char * get_env_value (varname) char *varname; { return ((char *)getenv (varname)); } char * get_home_dir () { char *home_dir; struct passwd *entry; home_dir = (char *)NULL; entry = getpwuid (getuid ()); if (entry) home_dir = entry->pw_dir; return (home_dir); } --- NEW FILE: README --- If you're building this separately from bash or the readline library, add $(srcdir)/shell.c to the CSOURCES variable and shell.o to the OBJECTS variable in Makefile.in. (Not that this is very useful without readline or bash.) --- NEW FILE: Makefile.in --- ## -*- text -*- #################################################### # # # Makefile for the GNU Tilde Library. # # # #################################################################### # Copyright (C) 1996 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. srcdir = @srcdir@ VPATH = .:@srcdir@ topdir = @top_srcdir@ BUILD_DIR = @BUILD_DIR@ INSTALL = @INSTALL@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_DATA = @INSTALL_DATA@ CC = @CC@ RANLIB = @RANLIB@ AR = @AR@ ARFLAGS = @ARFLAGS@ RM = rm CP = cp MV = mv SHELL = @MAKE_SHELL@ PROFILE_FLAGS = @PROFILE_FLAGS@ CFLAGS = @CFLAGS@ LOCAL_CFLAGS = @LOCAL_CFLAGS@ CPPFLAGS = @CPPFLAGS@ LDFLAGS = @LDFLAGS@ @LOCAL_LDFLAGS@ DEFS = @DEFS@ LOCAL_DEFS = @LOCAL_DEFS@ BASHINCDIR = ${topdir}/include INCLUDES = -I. -I../.. -I$(topdir) -I${BASHINCDIR} -I$(topdir)/lib CCFLAGS = $(PROFILE_FLAGS) $(DEFS) $(LOCAL_DEFS) $(CPPFLAGS) \ ${INCLUDES} $(LOCAL_CFLAGS) $(CFLAGS) .c.o: $(CC) -c $(CCFLAGS) $< # The name of the library target. LIBRARY_NAME = libtilde.a # The C code source files for this library. CSOURCES = $(srcdir)/tilde.c # The header files for this library. HSOURCES = $(srcdir)/tilde.h OBJECTS = tilde.o # The texinfo files which document this library. DOCSOURCE = doc/tilde.texi DOCOBJECT = doc/tilde.dvi DOCSUPPORT = doc/Makefile DOCUMENTATION = $(DOCSOURCE) $(DOCOBJECT) $(DOCSUPPORT) SUPPORT = Makefile ChangeLog $(DOCSUPPORT) SOURCES = $(CSOURCES) $(HSOURCES) $(DOCSOURCE) THINGS_TO_TAR = $(SOURCES) $(SUPPORT) ###################################################################### all: $(LIBRARY_NAME) $(LIBRARY_NAME): $(OBJECTS) $(RM) -f $@ $(AR) $(ARFLAGS) $@ $(OBJECTS) -test -n "$(RANLIB)" && $(RANLIB) $@ documentation: force -(cd doc; $(MAKE) $(MFLAGS)) force: # The rule for 'includes' is written funny so that the if statement # always returns TRUE unless there really was an error installing the # include files. install: $(INSTALL_DATA) -c -m 644 $(LIBRARY_NAME) $(libdir)/$(LIBRARY_NAME) -test -n "$(RANLIB)" && $(RANLIB) -t $(libdir)/$(LIBRARY_NAME) clean: $(RM) -f $(OBJECTS) $(LIBRARY_NAME) -( cd doc && $(MAKE) $(MFLAGS) $@ ) realclean distclean maintainer-clean: clean -( cd doc && $(MAKE) $(MFLAGS) $@ ) $(RM) -f Makefile mostlyclean: clean -( cd doc && $(MAKE) $(MFLAGS) $@ ) ###################################################################### # # # Dependencies for the object files which make up this library. # # # ###################################################################### tilde.o: tilde.h $(BASHINCDIR)/ansi_stdlib.h tilde.o: $(BUILD_DIR)/config.h # Rules for deficient makes, like SunOS and Solaris tilde.o: tilde.c --- NEW FILE: tilde.c --- /* tilde.c -- Tilde expansion code (~/foo := $HOME/foo). */ /* Copyright (C) 1988,1989 Free Software Foundation, Inc. This file is part of GNU Readline, a library for reading lines of text with interactive input and history editing. Readline is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Readline is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Readline; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if defined (HAVE_CONFIG_H) # include <config.h> #endif #if defined (HAVE_UNISTD_H) # ifdef _MINIX # include <sys/types.h> # endif # include <unistd.h> #endif #if defined (HAVE_STRING_H) # include <string.h> #else /* !HAVE_STRING_H */ # include <strings.h> #endif /* !HAVE_STRING_H */ #if defined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif /* HAVE_STDLIB_H */ #include <sys/types.h> #include <pwd.h> #include "tilde.h" #if defined (TEST) || defined (STATIC_MALLOC) static void *xmalloc (), *xrealloc (); #else # include "xmalloc.h" #endif /* TEST || STATIC_MALLOC */ #if !defined (HAVE_GETPW_DECLS) extern struct passwd *getpwuid PARAMS((uid_t)); extern struct passwd *getpwnam PARAMS((const char *)); #endif /* !HAVE_GETPW_DECLS */ #if !defined (savestring) #define savestring(x) strcpy ((char *)xmalloc (1 + strlen (x)), (x)) #endif /* !savestring */ #if !defined (NULL) # if defined (__STDC__) # define NULL ((void *) 0) # else # define NULL 0x0 # endif /* !__STDC__ */ #endif /* !NULL */ /* If being compiled as part of bash, these will be satisfied from variables.o. If being compiled as part of readline, they will be satisfied from shell.o. */ extern char *sh_get_home_dir PARAMS((void)); extern char *sh_get_env_value PARAMS((const char *)); /* The default value of tilde_additional_prefixes. This is set to whitespace preceding a tilde so that simple programs which do not perform any word separation get desired behaviour. */ static const char *default_prefixes[] = { " ~", "\t~", (const char *)NULL }; /* The default value of tilde_additional_suffixes. This is set to whitespace or newline so that simple programs which do not perform any word separation get desired behaviour. */ static const char *default_suffixes[] = { " ", "\n", (const char *)NULL }; /* If non-null, this contains the address of a function that the application wants called before trying the standard tilde expansions. The function is called with the text sans tilde, and returns a malloc()'ed string which is the expansion, or a NULL pointer if the expansion fails. */ tilde_hook_func_t *tilde_expansion_preexpansion_hook = (tilde_hook_func_t *)NULL; /* If non-null, this contains the address of a function to call if the standard meaning for expanding a tilde fails. The function is called with the text (sans tilde, as in "foo"), and returns a malloc()'ed string which is the expansion, or a NULL pointer if there is no expansion. */ tilde_hook_func_t *tilde_expansion_failure_hook = (tilde_hook_func_t *)NULL; /* When non-null, this is a NULL terminated array of strings which are duplicates for a tilde prefix. Bash uses this to expand `=~' and `:~'. */ char **tilde_additional_prefixes = (char **)default_prefixes; /* When non-null, this is a NULL terminated array of strings which match the end of a username, instead of just "/". Bash sets this to `:' and `=~'. */ char **tilde_additional_suffixes = (char **)default_suffixes; static int tilde_find_prefix PARAMS((const char *, int *)); static int tilde_find_suffix PARAMS((const char *)); static char *isolate_tilde_prefix PARAMS((const char *, int *)); static char *glue_prefix_and_suffix PARAMS((char *, const char *, int)); /* Find the start of a tilde expansion in STRING, and return the index of the tilde which starts the expansion. Place the length of the text which identified this tilde starter in LEN, excluding the tilde itself. */ static int tilde_find_prefix (string, len) const char *string; int *len; { register int i, j, string_len; register char **prefixes; prefixes = tilde_additional_prefixes; string_len = strlen (string); *len = 0; if (*string == '\0' || *string == '~') return (0); if (prefixes) { for (i = 0; i < string_len; i++) { for (j = 0; prefixes[j]; j++) { if (strncmp (string + i, prefixes[j], strlen (prefixes[j])) == 0) { *len = strlen (prefixes[j]) - 1; return (i + *len); } } } } return (string_len); } /* Find the end of a tilde expansion in STRING, and return the index of the character which ends the tilde definition. */ static int tilde_find_suffix (string) const char *string; { register int i, j, string_len; register char **suffixes; suffixes = tilde_additional_suffixes; string_len = strlen (string); for (i = 0; i < string_len; i++) { #if defined (__MSDOS__) if (string[i] == '/' || string[i] == '\\' /* || !string[i] */) #else if (string[i] == '/' /* || !string[i] */) #endif break; for (j = 0; suffixes && suffixes[j]; j++) { if (strncmp (string + i, suffixes[j], strlen (suffixes[j])) == 0) return (i); } } return (i); } /* Return a new string which is the result of tilde expanding STRING. */ char * tilde_expand (string) const char *string; { char *result; int result_size, result_index; result_index = result_size = 0; if (result = strchr (string, '~')) result = (char *)xmalloc (result_size = (strlen (string) + 16)); else result = (char *)xmalloc (result_size = (strlen (string) + 1)); /* Scan through STRING expanding tildes as we come to them. */ while (1) { register int start, end; char *tilde_word, *expansion; int len; /* Make START point to the tilde which starts the expansion. */ start = tilde_find_prefix (string, &len); /* Copy the skipped text into the result. */ if ((result_index + start + 1) > result_size) result = (char *)xrealloc (result, 1 + (result_size += (start + 20))); strncpy (result + result_index, string, start); result_index += start; /* Advance STRING to the starting tilde. */ string += start; /* Make END be the index of one after the last character of the username. */ end = tilde_find_suffix (string); /* If both START and END are zero, we are all done. */ if (!start && !end) break; /* Expand the entire tilde word, and copy it into RESULT. */ tilde_word = (char *)xmalloc (1 + end); strncpy (tilde_word, string, end); tilde_word[end] = '\0'; string += end; expansion = tilde_expand_word (tilde_word); free (tilde_word); len = strlen (expansion); #ifdef __CYGWIN__ /* Fix for Cygwin to prevent ~user/xxx from expanding to //xxx when $HOME for `user' is /. On cygwin, // denotes a network drive. */ if (len > 1 || *expansion != '/' || *string != '/') #endif { if ((result_index + len + 1) > result_size) result = (char *)xrealloc (result, 1 + (result_size += (len + 20))); strcpy (result + result_index, expansion); result_index += len; } free (expansion); } result[result_index] = '\0'; return (result); } /* Take FNAME and return the tilde prefix we want expanded. If LENP is non-null, the index of the end of the prefix into FNAME is returned in the location it points to. */ static char * isolate_tilde_prefix (fname, lenp) const char *fname; int *lenp; { char *ret; int i; ret = (char *)xmalloc (strlen (fname)); #if defined (__MSDOS__) for (i = 1; fname[i] && fname[i] != '/' && fname[i] != '\\'; i++) #else for (i = 1; fname[i] && fname[i] != '/'; i++) #endif ret[i - 1] = fname[i]; ret[i - 1] = '\0'; if (lenp) *lenp = i; return ret; } /* Return a string that is PREFIX concatenated with SUFFIX starting at SUFFIND. */ static char * glue_prefix_and_suffix (prefix, suffix, suffind) char *prefix; const char *suffix; int suffind; { char *ret; int plen, slen; plen = (prefix && *prefix) ? strlen (prefix) : 0; slen = strlen (suffix + suffind); ret = (char *)xmalloc (plen + slen + 1); if (plen) strcpy (ret, prefix); strcpy (ret + plen, suffix + suffind); return ret; } /* Do the work of tilde expansion on FILENAME. FILENAME starts with a tilde. If there is no expansion, call tilde_expansion_failure_hook. This always returns a newly-allocated string, never static storage. */ char * tilde_expand_word (filename) const char *filename; { char *dirname, *expansion, *username; int user_len; struct passwd *user_entry; if (filename == 0) return ((char *)NULL); if (*filename != '~') return (savestring (filename)); /* A leading `~/' or a bare `~' is *always* translated to the value of $HOME or the home directory of the current user, regardless of any preexpansion hook. */ if (filename[1] == '\0' || filename[1] == '/') { /* Prefix $HOME to the rest of the string. */ expansion = sh_get_env_value ("HOME"); /* If there is no HOME variable, look up the directory in the password database. */ if (expansion == 0) expansion = sh_get_home_dir (); return (glue_prefix_and_suffix (expansion, filename, 1)); } username = isolate_tilde_prefix (filename, &user_len); if (tilde_expansion_preexpansion_hook) { expansion = (*tilde_expansion_preexpansion_hook) (username); if (expansion) { dirname = glue_prefix_and_suffix (expansion, filename, user_len); free (username); free (expansion); return (dirname); } } /* No preexpansion hook, or the preexpansion hook failed. Look in the password database. */ dirname = (char *)NULL; user_entry = getpwnam (username); if (user_entry == 0) { /* If the calling program has a special syntax for expanding tildes, and we couldn't find a standard expansion, then let them try. */ if (tilde_expansion_failure_hook) { expansion = (*tilde_expansion_failure_hook) (username); if (expansion) { dirname = glue_prefix_and_suffix (expansion, filename, user_len); free (expansion); } } free (username); /* If we don't have a failure hook, or if the failure hook did not expand the tilde, return a copy of what we were passed. */ if (dirname == 0) dirname = savestring (filename); } else { free (username); dirname = glue_prefix_and_suffix (user_entry->pw_dir, filename, user_len); } endpwent (); return (dirname); } #if defined (TEST) #undef NULL #include <stdio.h> main (argc, argv) int argc; char **argv; { char *result, line[512]; int done = 0; while (!done) { printf ("~expand: "); fflush (stdout); if (!gets (line)) strcpy (line, "done"); if ((strcmp (line, "done") == 0) || (strcmp (line, "quit") == 0) || (strcmp (line, "exit") == 0)) { done = 1; break; } result = tilde_expand (line); printf (" --> %s\n", result); free (result); } exit (0); } static void memory_error_and_abort (); static void * xmalloc (bytes) size_t bytes; { void *temp = (char *)malloc (bytes); if (!temp) memory_error_and_abort (); return (temp); } static void * xrealloc (pointer, bytes) void *pointer; int bytes; { void *temp; if (!pointer) temp = malloc (bytes); else temp = realloc (pointer, bytes); if (!temp) memory_error_and_abort (); return (temp); } static void memory_error_and_abort () { fprintf (stderr, "readline: out of virtual memory\n"); abort (); } /* * Local variables: * compile-command: "gcc -g -DTEST -o tilde tilde.c" * end: */ #endif /* TEST */ --- NEW FILE: tilde.h --- /* tilde.h: Externally available variables and function in libtilde.a. */ /* Copyright (C) 1992 Free Software Foundation, Inc. This file contains the Readline Library (the Library), a set of routines for providing Emacs style line input to programs that ask for it. The Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_TILDE_H_) # define _TILDE_H_ #ifdef __cplusplus extern "C" { #endif /* A function can be defined using prototypes and compile on both ANSI C and traditional C compilers with something like this: extern char *func PARAMS((char *, char *, int)); */ #if !defined (PARAMS) # if defined (__STDC__) || defined (__GNUC__) || defined (__cplusplus) # define PARAMS(protos) protos # else # define PARAMS(protos) () # endif #endif typedef char *tilde_hook_func_t PARAMS((char *)); /* If non-null, this contains the address of a function that the application wants called before trying the standard tilde expansions. The function is called with the text sans tilde, and returns a malloc()'ed string which is the expansion, or a NULL pointer if the expansion fails. */ extern tilde_hook_func_t *tilde_expansion_preexpansion_hook; /* If non-null, this contains the address of a function to call if the standard meaning for expanding a tilde fails. The function is called with the text (sans tilde, as in "foo"), and returns a malloc()'ed string which is the expansion, or a NULL pointer if there is no expansion. */ extern tilde_hook_func_t *tilde_expansion_failure_hook; /* When non-null, this is a NULL terminated array of strings which are duplicates for a tilde prefix. Bash uses this to expand `=~' and `:~'. */ extern char **tilde_additional_prefixes; /* When non-null, this is a NULL terminated array of strings which match the end of a username, instead of just "/". Bash sets this to `:' and `=~'. */ extern char **tilde_additional_suffixes; /* Return a new string which is the result of tilde expanding STRING. */ extern char *tilde_expand PARAMS((const char *)); /* Do the work of tilde expansion on FILENAME. FILENAME starts with a tilde. If there is no expansion, call tilde_expansion_failure_hook. */ extern char *tilde_expand_word PARAMS((const char *)); #ifdef __cplusplus } #endif #endif /* _TILDE_H_ */ |
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/sh In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/sh Added Files: Makefile.in clktck.c clock.c fmtullong.c fmtulong.c fmtumax.c getcwd.c getenv.c inet_aton.c itos.c mailstat.c makepath.c memset.c mktime.c netconn.c netopen.c oslib.c pathcanon.c pathphys.c rename.c setlinebuf.c shquote.c shtty.c snprintf.c spell.c strcasecmp.c strerror.c strftime.c strindex.c stringlist.c stringvec.c strpbrk.c strtod.c strtoimax.c strtol.c strtoll.c strtoul.c strtoull.c strtoumax.c strtrans.c times.c timeval.c tmpfile.c vprint.c xstrchr.c zcatfd.c zread.c zwrite.c Log Message: Pristine source --- NEW FILE: mailstat.c --- /* mailstat.c -- stat a mailbox file, handling maildir-type mail directories */ /* Copyright (C) 2001 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #include <stdio.h> #include <errno.h> #include <bashtypes.h> #include <posixstat.h> #include <posixdir.h> #include <bashansi.h> #ifndef _MINIX # include <sys/param.h> #endif #include <maxpath.h> /* * Stat a file. If it's a maildir, check all messages * in the maildir and present the grand total as a file. * The fields in the 'struct stat' are from the mail directory. * The following fields are emulated: * * st_nlink always 1, unless st_blocks is not present, in which case it's * the total number of messages * st_size total number of bytes in all files * st_blocks total number of messages, if present in struct stat * st_atime access time of newest file in maildir * st_mtime modify time of newest file in maildir * st_mode S_IFDIR changed to S_IFREG * * This is good enough for most mail-checking applications. */ int mailstat(path, st) const char *path; struct stat *st; { static struct stat st_new_last, st_ret_last; struct stat st_ret, st_tmp; DIR *dd; struct dirent *fn; char dir[PATH_MAX * 2], file[PATH_MAX * 2]; int i, l; time_t atime, mtime; atime = mtime = 0; /* First see if it's a directory. */ if ((i = stat(path, st)) != 0 || S_ISDIR(st->st_mode) == 0) return i; if (strlen(path) > sizeof(dir) - 5) { #ifdef ENAMETOOLONG errno = ENAMETOOLONG; #else errno = EINVAL; #endif return -1; } st_ret = *st; st_ret.st_nlink = 1; st_ret.st_size = 0; #ifdef HAVE_STRUCT_STAT_ST_BLOCKS st_ret.st_blocks = 0; #else st_ret.st_nlink = 0; #endif st_ret.st_mode &= ~S_IFDIR; st_ret.st_mode |= S_IFREG; /* See if cur/ is present */ sprintf(dir, "%s/cur", path); if (stat(dir, &st_tmp) || S_ISDIR(st_tmp.st_mode) == 0) return 0; st_ret.st_atime = st_tmp.st_atime; /* See if tmp/ is present */ sprintf(dir, "%s/tmp", path); if (stat(dir, &st_tmp) || S_ISDIR(st_tmp.st_mode) == 0) return 0; st_ret.st_mtime = st_tmp.st_mtime; /* And new/ */ sprintf(dir, "%s/new", path); if (stat(dir, &st_tmp) || S_ISDIR(st_tmp.st_mode) == 0) return 0; st_ret.st_mtime = st_tmp.st_mtime; /* Optimization - if new/ didn't change, nothing else did. */ if (st_tmp.st_dev == st_new_last.st_dev && st_tmp.st_ino == st_new_last.st_ino && st_tmp.st_atime == st_new_last.st_atime && st_tmp.st_mtime == st_new_last.st_mtime) { *st = st_ret_last; return 0; } st_new_last = st_tmp; /* Loop over new/ and cur/ */ for (i = 0; i < 2; i++) { sprintf(dir, "%s/%s", path, i ? "cur" : "new"); sprintf(file, "%s/", dir); l = strlen(file); if ((dd = opendir(dir)) == NULL) return 0; while ((fn = readdir(dd)) != NULL) { if (fn->d_name[0] == '.' || strlen(fn->d_name) + l >= sizeof(file)) continue; strcpy(file + l, fn->d_name); if (stat(file, &st_tmp) != 0) continue; st_ret.st_size += st_tmp.st_size; #ifdef HAVE_STRUCT_STAT_ST_BLOCKS st_ret.st_blocks++; #else st_ret.st_nlink++; #endif if (st_tmp.st_atime != st_tmp.st_mtime && st_tmp.st_atime > atime) atime = st_tmp.st_atime; if (st_tmp.st_mtime > mtime) mtime = st_tmp.st_mtime; } closedir(dd); } if (atime) st_ret.st_atime = atime; if (mtime) st_ret.st_mtime = mtime; *st = st_ret_last = st_ret; return 0; } --- NEW FILE: netopen.c --- /* * netopen.c -- functions to make tcp/udp connections * * Chet Ramey * ch...@in... */ /* Copyright (C) 1987-2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #if defined (HAVE_NETWORK) #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #include <stdio.h> #include <sys/types.h> #if defined (HAVE_SYS_SOCKET_H) # include <sys/socket.h> #endif #if defined (HAVE_NETINET_IN_H) # include <netinet/in.h> #endif #if defined (HAVE_NETDB_H) # include <netdb.h> #endif #if defined (HAVE_ARPA_INET_H) # include <arpa/inet.h> #endif #include <bashansi.h> #include <errno.h> #include <shell.h> #include <xmalloc.h> #ifndef errno extern int errno; #endif #if !defined (HAVE_INET_ATON) extern int inet_aton __P((const char *, struct in_addr *)); #endif #ifndef HAVE_GETADDRINFO /* Stuff the internet address corresponding to HOST into AP, in network byte order. Return 1 on success, 0 on failure. */ static int _getaddr (host, ap) char *host; struct in_addr *ap; { struct hostent *h; int r; r = 0; if (host[0] >= '0' && host[0] <= '9') { /* If the first character is a digit, guess that it's an Internet address and return immediately if inet_aton succeeds. */ r = inet_aton (host, ap); if (r) return r; } #if !defined (HAVE_GETHOSTBYNAME) return 0; #else h = gethostbyname (host); if (h && h->h_addr) { bcopy(h->h_addr, (char *)ap, h->h_length); return 1; } #endif return 0; } /* Return 1 if SERV is a valid port number and stuff the converted value into PP in network byte order. */ static int _getserv (serv, proto, pp) char *serv; int proto; unsigned short *pp; { intmax_t l; unsigned short s; if (legal_number (serv, &l)) { s = (unsigned short)(l & 0xFFFF); if (s != l) return (0); s = htons (s); if (pp) *pp = s; return 1; } else #if defined (HAVE_GETSERVBYNAME) { struct servent *se; se = getservbyname (serv, (proto == 't') ? "tcp" : "udp"); if (se == 0) return 0; if (pp) *pp = se->s_port; /* ports returned in network byte order */ return 1; } #else /* !HAVE_GETSERVBYNAME */ return 0; #endif /* !HAVE_GETSERVBYNAME */ } /* * Open a TCP or UDP connection to HOST on port SERV. Uses the * traditional BSD mechanisms. Returns the connected socket or -1 on error. */ static int _netopen4(host, serv, typ) char *host, *serv; int typ; { struct in_addr ina; struct sockaddr_in sin; unsigned short p; int s, e; if (_getaddr(host, &ina) == 0) { internal_error ("%s: host unknown", host); errno = EINVAL; return -1; } if (_getserv(serv, typ, &p) == 0) { internal_error("%s: invalid service", serv); errno = EINVAL; return -1; } memset ((char *)&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = p; sin.sin_addr = ina; s = socket(AF_INET, (typ == 't') ? SOCK_STREAM : SOCK_DGRAM, 0); if (s < 0) { sys_error ("socket"); return (-1); } if (connect (s, (struct sockaddr *)&sin, sizeof (sin)) < 0) { e = errno; sys_error("connect"); close(s); errno = e; return (-1); } return(s); } #endif /* ! HAVE_GETADDRINFO */ #ifdef HAVE_GETADDRINFO /* * Open a TCP or UDP connection to HOST on port SERV. Uses getaddrinfo(3) * which provides support for IPv6. Returns the connected socket or -1 * on error. */ static int _netopen6 (host, serv, typ) char *host, *serv; int typ; { int s, e; struct addrinfo hints, *res, *res0; int gerr; memset ((char *)&hints, 0, sizeof (hints)); /* XXX -- if problems with IPv6, set to PF_INET for IPv4 only */ #ifdef DEBUG /* PF_INET is the one that works for me */ hints.ai_family = PF_INET; #else hints.ai_family = PF_UNSPEC; #endif hints.ai_socktype = (typ == 't') ? SOCK_STREAM : SOCK_DGRAM; gerr = getaddrinfo (host, serv, &hints, &res0); if (gerr) { if (gerr == EAI_SERVICE) internal_error ("%s: %s", serv, gai_strerror (gerr)); else internal_error ("%s: %s", host, gai_strerror (gerr)); errno = EINVAL; return -1; } for (res = res0; res; res = res->ai_next) { if ((s = socket (res->ai_family, res->ai_socktype, res->ai_protocol)) < 0) { if (res->ai_next) continue; sys_error ("socket"); freeaddrinfo (res0); return -1; } if (connect (s, res->ai_addr, res->ai_addrlen) < 0) { if (res->ai_next) { close (s); continue; } e = errno; sys_error ("connect"); close (s); freeaddrinfo (res0); errno = e; return -1; } freeaddrinfo (res0); break; } return s; } #endif /* HAVE_GETADDRINFO */ /* * Open a TCP or UDP connection to HOST on port SERV. Uses getaddrinfo(3) * if available, falling back to the traditional BSD mechanisms otherwise. * Returns the connected socket or -1 on error. */ static int _netopen(host, serv, typ) char *host, *serv; int typ; { #ifdef HAVE_GETADDRINFO return (_netopen6 (host, serv, typ)); #else return (_netopen4 (host, serv, typ)); #endif } /* * Open a TCP or UDP connection given a path like `/dev/tcp/host/port' to * host `host' on port `port' and return the connected socket. */ int netopen (path) char *path; { char *np, *s, *t; int fd; np = (char *)xmalloc (strlen (path) + 1); strcpy (np, path); s = np + 9; t = strchr (s, '/'); if (t == 0) { internal_error ("%s: bad network path specification", path); return -1; } *t++ = '\0'; fd = _netopen (s, t, path[5]); free (np); return fd; } #if 0 /* * Open a TCP connection to host `host' on the port defined for service * `serv' and return the connected socket. */ int tcpopen (host, serv) char *host, *serv; { return (_netopen (host, serv, 't')); } /* * Open a UDP connection to host `host' on the port defined for service * `serv' and return the connected socket. */ int udpopen (host, serv) char *host, *serv; { return _netopen (host, serv, 'u'); } #endif #else /* !HAVE_NETWORK */ int netopen (path) char *path; { internal_error ("network operations not supported"); return -1; } #endif /* !HAVE_NETWORK */ --- NEW FILE: strtoumax.c --- /* Convert string representation of a number into an uintmax_t value. Copyright 1999, 2001 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Written by Paul Eggert. Modified by Chet Ramey for Bash. */ #if HAVE_CONFIG_H # include <config.h> #endif #if HAVE_INTTYPES_H # include <inttypes.h> #endif #if HAVE_STDLIB_H # include <stdlib.h> #endif #include <stdc.h> /* Verify a requirement at compile-time (unlike assert, which is runtime). */ #define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; } #ifndef HAVE_DECL_STRTOUL "this configure-time declaration test was not run" #endif #if !HAVE_DECL_STRTOUL extern unsigned long strtoul __P((const char *, char **, int)); #endif #ifndef HAVE_DECL_STRTOULL "this configure-time declaration test was not run" #endif #if !HAVE_DECL_STRTOULL && HAVE_UNSIGNED_LONG_LONG extern unsigned long long strtoull __P((const char *, char **, int)); #endif uintmax_t strtoumax (ptr, endptr, base) const char *ptr; char **endptr; int base; { #if HAVE_UNSIGNED_LONG_LONG verify (size_is_that_of_unsigned_long_or_unsigned_long_long, (sizeof (uintmax_t) == sizeof (unsigned long) || sizeof (uintmax_t) == sizeof (unsigned long long))); if (sizeof (uintmax_t) != sizeof (unsigned long)) return (strtoull (ptr, endptr, base)); #else verify (size_is_that_of_unsigned_long, sizeof (uintmax_t) == sizeof (unsigned long)); #endif return (strtoul (ptr, endptr, base)); } #ifdef TESTING # include <stdio.h> int main () { char *p, *endptr; uintmax_t x; #if HAVE_UNSIGNED_LONG_LONG unsigned long long y; #endif unsigned long z; printf ("sizeof uintmax_t: %d\n", sizeof (uintmax_t)); #if HAVE_UNSIGNED_LONG_LONG printf ("sizeof unsigned long long: %d\n", sizeof (unsigned long long)); #endif printf ("sizeof unsigned long: %d\n", sizeof (unsigned long)); x = strtoumax("42", &endptr, 10); #if HAVE_LONG_LONG y = strtoull("42", &endptr, 10); #else y = 0; #endif z = strtoul("42", &endptr, 10); printf ("%llu %llu %lu\n", x, y, z); exit (0); } #endif --- NEW FILE: strtod.c --- /* Copyright (C) 1991, 1992 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #if HAVE_CONFIG_H # include <config.h> #endif #ifndef HAVE_STRTOD #include <errno.h> #ifndef errno extern int errno; #endif #include <chartypes.h> #include <math.h> #if HAVE_FLOAT_H # include <float.h> #else # define DBL_MAX 1.7976931348623159e+308 # define DBL_MIN 2.2250738585072010e-308 #endif #include <bashansi.h> #ifndef NULL # define NULL 0 #endif #ifndef HUGE_VAL # define HUGE_VAL HUGE #endif /* Convert NPTR to a double. If ENDPTR is not NULL, a pointer to the character after the last one used in the number is put in *ENDPTR. */ double strtod (nptr, endptr) const char *nptr; char **endptr; { register const char *s; short sign; /* The number so far. */ double num; int got_dot; /* Found a decimal point. */ int got_digit; /* Seen any digits. */ /* The exponent of the number. */ long int exponent; if (nptr == NULL) { errno = EINVAL; goto noconv; } s = nptr; /* Eat whitespace. */ while (ISSPACE ((unsigned char)*s)) ++s; /* Get the sign. */ sign = *s == '-' ? -1 : 1; if (*s == '-' || *s == '+') ++s; num = 0.0; got_dot = 0; got_digit = 0; exponent = 0; for (;; ++s) { if (DIGIT (*s)) { got_digit = 1; /* Make sure that multiplication by 10 will not overflow. */ if (num > DBL_MAX * 0.1) /* The value of the digit doesn't matter, since we have already gotten as many digits as can be represented in a `double'. This doesn't necessarily mean the result will overflow. The exponent may reduce it to within range. We just need to record that there was another digit so that we can multiply by 10 later. */ ++exponent; else num = (num * 10.0) + (*s - '0'); /* Keep track of the number of digits after the decimal point. If we just divided by 10 here, we would lose precision. */ if (got_dot) --exponent; } else if (!got_dot && *s == '.') /* Record that we have found the decimal point. */ got_dot = 1; else /* Any other character terminates the number. */ break; } if (!got_digit) goto noconv; if (TOLOWER ((unsigned char)*s) == 'e') { /* Get the exponent specified after the `e' or `E'. */ int save = errno; char *end; long int exp; errno = 0; ++s; exp = strtol (s, &end, 10); if (errno == ERANGE) { /* The exponent overflowed a `long int'. It is probably a safe assumption that an exponent that cannot be represented by a `long int' exceeds the limits of a `double'. */ if (endptr != NULL) *endptr = end; if (exp < 0) goto underflow; else goto overflow; } else if (end == s) /* There was no exponent. Reset END to point to the 'e' or 'E', so *ENDPTR will be set there. */ end = (char *) s - 1; errno = save; s = end; exponent += exp; } if (endptr != NULL) *endptr = (char *) s; if (num == 0.0) return 0.0; /* Multiply NUM by 10 to the EXPONENT power, checking for overflow and underflow. */ if (exponent < 0) { if (num < DBL_MIN * pow (10.0, (double) -exponent)) goto underflow; } else if (exponent > 0) { if (num > DBL_MAX * pow (10.0, (double) -exponent)) goto overflow; } num *= pow (10.0, (double) exponent); return num * sign; overflow: /* Return an overflow error. */ errno = ERANGE; return HUGE_VAL * sign; underflow: /* Return an underflow error. */ if (endptr != NULL) *endptr = (char *) nptr; errno = ERANGE; return 0.0; noconv: /* There was no number. */ if (endptr != NULL) *endptr = (char *) nptr; return 0.0; } #endif /* !HAVE_STRTOD */ --- NEW FILE: Makefile.in --- # # Makefile for the Bash library # # # Copyright (C) 1998-2002 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. srcdir = @srcdir@ VPATH = .:@srcdir@ topdir = @top_srcdir@ BUILD_DIR = @BUILD_DIR@ BASHINCDIR = ${topdir}/include INSTALL = @INSTALL@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_DATA = @INSTALL_DATA@ CC = @CC@ RANLIB = @RANLIB@ AR = @AR@ ARFLAGS = @ARFLAGS@ RM = rm -f CP = cp MV = mv SHELL = @MAKE_SHELL@ CFLAGS = @CFLAGS@ LOCAL_CFLAGS = @LOCAL_CFLAGS@ ${DEBUG} CPPFLAGS = @CPPFLAGS@ LDFLAGS = @LDFLAGS@ @LOCAL_LDFLAGS@ PROFILE_FLAGS = @PROFILE_FLAGS@ DEFS = @DEFS@ LOCAL_DEFS = @LOCAL_DEFS@ INCLUDES = -I. -I../.. -I$(topdir) -I$(topdir)/lib -I$(BASHINCDIR) -I$(srcdir) CCFLAGS = ${PROFILE_FLAGS} ${INCLUDES} $(DEFS) $(LOCAL_DEFS) $(LOCAL_CFLAGS) \ $(CFLAGS) $(CPPFLAGS) GCC_LINT_FLAGS = -Wall -Wshadow -Wpointer-arith -Wcast-qual \ -Wcast-align -Wstrict-prototypes -Wconversion \ -Wmissing-prototypes -Wtraditional -Wredundant-decls -pedantic .c.o: $(CC) -c $(CCFLAGS) $< # The name of the library target. LIBRARY_NAME = libsh.a # The C code source files for this library. CSOURCES = clktck.c clock.c getcwd.c getenv.c oslib.c setlinebuf.c \ strcasecmp.c strerror.c strtod.c strtol.c strtoul.c \ vprint.c itos.c rename.c zread.c zwrite.c shtty.c \ inet_aton.c netconn.c netopen.c strpbrk.c timeval.c makepath.c \ pathcanon.c pathphys.c tmpfile.c stringlist.c stringvec.c spell.c \ shquote.c strtrans.c strindex.c snprintf.c mailstat.c \ fmtulong.c fmtullong.c fmtumax.c \ strtoll.c strtoull.c strtoimax.c strtoumax.c memset.c \ mktime.c strftime.c xstrchr.c zcatfd.c # The header files for this library. HSOURCES = # The object files contained in $(LIBRARY_NAME) LIBOBJS = @LIBOBJS@ OBJECTS = clktck.o clock.o getenv.o oslib.o setlinebuf.o \ itos.o zread.o zwrite.o shtty.o \ netconn.o netopen.o timeval.o makepath.o pathcanon.o \ pathphys.o tmpfile.o stringlist.o stringvec.o spell.o shquote.o \ strtrans.o strindex.o snprintf.o mailstat.o fmtulong.o \ fmtullong.o fmtumax.o xstrchr.o zcatfd.o ${LIBOBJS} SUPPORT = Makefile all: $(LIBRARY_NAME) $(LIBRARY_NAME): $(OBJECTS) $(RM) $@ $(AR) $(ARFLAGS) $@ $(OBJECTS) -test -n "$(RANLIB)" && $(RANLIB) $@ force: # The rule for 'includes' is written funny so that the if statement # always returns TRUE unless there really was an error installing the # include files. install: clean: $(RM) $(OBJECTS) $(LIBRARY_NAME) realclean distclean maintainer-clean: clean $(RM) Makefile mostlyclean: clean # Dependencies # rules for losing makes, like SunOS clktck.o: clktck.c clock.o: clock.c fmtullong.o: fmtullong.c fmtulong.o: fmtulong.c fmtumax.o: fmtumax.c getcwd.o: getcwd.c getenv.o: getenv.c inet_aton.o: inet_aton.c itos.o: itos.c mailstat.o: mailstat.c makepath.o: makepath.c memset.o: memset.c mktime.o: mktime.c netconn.o: netconn.c netopen.o: netopen.c oslib.o: oslib.c pathcanon.o: pathcanon.c pathphys.o: pathphys.c rename.o: rename.c setlinebuf.o: setlinebuf.c shquote.o: shquote.c shtty.o: shtty.c snprintf.o: snprintf.c spell.o: spell.c strcasecmp.o: strcasecmp.c strerror.o: strerror.c strftime.o: strftime.c strindex.o: strindex.c stringlist.o: stringlist.c stringvec.o: stringvec.c strpbrk.o: strpbrk.c strtod.o: strtod.c strtoimax.o: strtoimax.c strtol.o: strtol.c strtoll.o: strtoll.c strtoul.o: strtoul.c strtoull.o: strtoull.c strtoumax.o: strtoumax.c strtrans.o: strtrans.c times.o: times.c timeval.o: timeval.c tmpfile.o: tmpfile.c vprint.o: vprint.c xstrchr.o: xstrchr.c zcatfd.o: zcatfd.c zread.o: zread.c zwrite.o: zwrite.c # dependencies for c files that include other c files fmtullong.o: fmtulong.c fmtumax.o: fmtulong.c strtoll.o: strtol.c strtoul.o: strtol.c strtoull.o: strtol.c # all files in the library depend on config.h clktck.o: ${BUILD_DIR}/config.h clock.o: ${BUILD_DIR}/config.h fmtullong.o: ${BUILD_DIR}/config.h fmtulong.o: ${BUILD_DIR}/config.h fmtumax.o: ${BUILD_DIR}/config.h getcwd.o: ${BUILD_DIR}/config.h getenv.o: ${BUILD_DIR}/config.h inet_aton.o: ${BUILD_DIR}/config.h itos.o: ${BUILD_DIR}/config.h mailstat.o: ${BUILD_DIR}/config.h makepath.o: ${BUILD_DIR}/config.h memset.o: ${BUILD_DIR}/config.h mktime.o: ${BUILD_DIR}/config.h netconn.o: ${BUILD_DIR}/config.h netopen.o: ${BUILD_DIR}/config.h oslib.o: ${BUILD_DIR}/config.h pathcanon.o: ${BUILD_DIR}/config.h pathphys.o: ${BUILD_DIR}/config.h rename.o: ${BUILD_DIR}/config.h setlinebuf.o: ${BUILD_DIR}/config.h shquote.o: ${BUILD_DIR}/config.h shtty.o: ${BUILD_DIR}/config.h snprintf.o: ${BUILD_DIR}/config.h spell.o: ${BUILD_DIR}/config.h strcasecmp.o: ${BUILD_DIR}/config.h strerror.o: ${BUILD_DIR}/config.h strftime.o: ${BUILD_DIR}/config.h strindex.o: ${BUILD_DIR}/config.h stringlist.o: ${BUILD_DIR}/config.h stringvec.o: ${BUILD_DIR}/config.h strpbrk.o: ${BUILD_DIR}/config.h strtod.o: ${BUILD_DIR}/config.h strtoimax.o: ${BUILD_DIR}/config.h strtol.o: ${BUILD_DIR}/config.h strtoll.o: ${BUILD_DIR}/config.h strtoul.o: ${BUILD_DIR}/config.h strtoull.o: ${BUILD_DIR}/config.h strtoumax.o: ${BUILD_DIR}/config.h strtrans.o: ${BUILD_DIR}/config.h times.o: ${BUILD_DIR}/config.h timeval.o: ${BUILD_DIR}/config.h tmpfile.o: ${BUILD_DIR}/config.h vprint.o: ${BUILD_DIR}/config.h xstrchr.o: ${BUILD_DIR}/config.h zcatfd.o: ${BUILD_DIR}/config.h zread.o: ${BUILD_DIR}/config.h zwrite.o: ${BUILD_DIR}/config.h clktck.o: ${topdir}/bashtypes.h getcwd.o: ${topdir}/bashtypes.h ${topdir}/bashansi.h ${BASHINCDIR}/maxpath.h getcwd.o: ${BASHINCDIR}/posixstat.h ${BASHINCDIR}/posixdir.h getcwd.o: ${BASHINCDIR}/memalloc.h ${BASHINCDIR}/ansi_stdlib.h getenv.o: ${topdir}/bashansi.h ${BASHINCDIR}/ansi_stdlib.h getenv.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h getenv.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h getenv.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h getenv.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h getenv.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h getenv.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h getenv.o: ${topdir}/pathnames.h ${topdir}/externs.h inet_aton.o: ${topdir}/bashansi.h ${BASHINCDIR}/ansi_stdlib.h inet_aton.o: ${BASHINCDIR}/stdc.h itos.o: ${topdir}/bashansi.h ${BASHINCDIR}/ansi_stdlib.h itos.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h itos.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h itos.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h itos.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h itos.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h itos.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h itos.o: ${topdir}/pathnames.h ${topdir}/externs.h makepath.o: ${topdir}/bashansi.h ${BASHINCDIR}/ansi_stdlib.h makepath.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h makepath.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h makepath.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h makepath.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h makepath.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h makepath.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h makepath.o: ${topdir}/pathnames.h ${topdir}/externs.h netconn.o: ${BASHINCDIR}/posixstat.h ${BASHINCDIR}/filecntl.h netconn.o: ${topdir}/bashtypes.h netopen.o: ${topdir}/bashansi.h ${BASHINCDIR}/ansi_stdlib.h ${topdir}/xmalloc.h netopen.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h netopen.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h netopen.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h netopen.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h netopen.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h netopen.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h netopen.o: ${topdir}/pathnames.h ${topdir}/externs.h oslib.o: ${topdir}/bashtypes.h ${topdir}/bashansi.h ${BASHINCDIR}/maxpath.h oslib.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h oslib.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h oslib.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h oslib.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h oslib.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h oslib.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h oslib.o: ${topdir}/pathnames.h ${topdir}/externs.h oslib.o: ${BASHINCDIR}/posixstat.h ${BASHINCDIR}/filecntl.h oslib.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h pathcanon.o: ${topdir}/bashtypes.h ${topdir}/bashansi.h ${BASHINCDIR}/maxpath.h pathcanon.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h pathcanon.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h pathcanon.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h pathcanon.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h pathcanon.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h pathcanon.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h pathcanon.o: ${topdir}/pathnames.h ${topdir}/externs.h pathcanon.o: ${BASHINCDIR}/posixstat.h ${BASHINCDIR}/filecntl.h pathcanon.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h pathphys.o: ${topdir}/bashtypes.h ${topdir}/bashansi.h ${BASHINCDIR}/maxpath.h pathphys.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h pathphys.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h pathphys.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h pathphys.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h pathphys.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h pathphys.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h pathphys.o: ${topdir}/pathnames.h ${topdir}/externs.h pathphys.o: ${BASHINCDIR}/posixstat.h ${BASHINCDIR}/filecntl.h pathphys.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h rename.o: ${topdir}/bashtypes.h ${BASHINCDIR}/stdc.h rename.o: ${BASHINCDIR}/posixstat.h setlinebuf.o: ${topdir}/xmalloc.h ${topdir}/bashansi.h setlinebuf.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/stdc.h shquote.o: ${BASHINCDIR}/stdc.h ${topdir}/bashansi.h shquote.o: ${BASHINCDIR}/ansi_stdlib.h ${topdir}/xmalloc.h shtty.o: ${BASHINCDIR}/shtty.h shtty.o: ${BASHINCDIR}/stdc.h snprintf.o: ${BASHINCDIR}/stdc.h ${topdir}/bashansi.h ${topdir}/xmalloc.h snprintf.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h snprintf.o: ${BASHINCDIR}/typemax.h spell.o: ${topdir}/bashtypes.h spell.o: ${BASHINCDIR}/posixstat.h ${BASHINCDIR}/posixdir.h spell.o: ${BASHINCDIR}/ansi_stdlib.h strcasecmp.o: ${BASHINCDIR}/stdc.h ${topdir}/bashansi.h strcasecmp.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h strerror.o: ${topdir}/bashtypes.h strerror.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h strerror.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h strerror.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h strerror.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h strerror.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h strerror.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h strerror.o: ${topdir}/pathnames.h ${topdir}/externs.h strindex.o: ${BASHINCDIR}/stdc.h ${topdir}/bashansi.h strindex.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h stringlist.o: ${topdir}/bashansi.h stringlist.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h stringlist.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h stringlist.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h stringlist.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h stringlist.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h stringlist.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h stringlist.o: ${topdir}/pathnames.h ${topdir}/externs.h stringvec.o: ${topdir}/bashansi.h ${BASHINCDIR}/chartypes.h stringvec.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h stringvec.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h stringvec.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h stringvec.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h stringvec.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h stringvec.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h stringvec.o: ${topdir}/pathnames.h ${topdir}/externs.h strpbrk.o: ${BASHINCDIR}/stdc.h strtod.o: ${topdir}/bashansi.h strtod.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h strtoimax.o: ${BASHINCDIR}/stdc.h strtol.o: ${topdir}/bashansi.h strtol.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h strtol.o: ${BASHINCDIR}/typemax.h strtoll.o: ${topdir}/bashansi.h strtoll.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h strtoll.o: ${BASHINCDIR}/typemax.h strtoul.o: ${topdir}/bashansi.h strtoul.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h strtoul.o: ${BASHINCDIR}/typemax.h strtoull.o: ${topdir}/bashansi.h strtoull.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h strtoull.o: ${BASHINCDIR}/typemax.h strtoumax.o: ${BASHINCDIR}/stdc.h strtrans.o: ${topdir}/bashansi.h strtrans.o: ${BASHINCDIR}/ansi_stdlib.h ${BASHINCDIR}/chartypes.h strtrans.o: ${topdir}/shell.h ${topdir}/syntax.h ${topdir}/bashjmp.h ${BASHINCDIR}/posixjmp.h strtrans.o: ${topdir}/command.h ${BASHINCDIR}/stdc.h ${topdir}/error.h strtrans.o: ${topdir}/general.h ${topdir}/bashtypes.h ${topdir}/variables.h ${topdir}/conftypes.h strtrans.o: ${topdir}/array.h ${topdir}/hashlib.h ${topdir}/quit.h strtrans.o: ${topdir}/unwind_prot.h ${topdir}/dispose_cmd.h strtrans.o: ${topdir}/make_cmd.h ${topdir}/subst.h ${topdir}/sig.h strtrans.o: ${topdir}/pathnames.h ${topdir}/externs.h times.o: ${BASHINCDIR}/systimes.h times.o: ${BASHINCDIR}/posixtime.h timeval.o: ${BASHINCDIR}/posixtime.h tmpfile.o: ${topdir}/bashtypes.h tmpfile.o: ${BASHINCDIR}/posixstat.h tmpfile.o: ${BASHINCDIR}/filecntl.h clock.o: ${BASHINCDIR}/posixtime.h mailstat.o: ${topdir}/bashansi.h mailstat.o: ${topdir}/bashtypes.h mailstat.o: ${BASHINCDIR}/ansi_stdlib.h mailstat.o: ${BASHINCDIR}/posixstat.h mailstat.o: ${BASHINCDIR}/posixdir.h mailstat.o: ${BASHINCDIR}/maxpath.h fmtulong.o: ${topdir}/bashansi.h fmtulong.o: ${BASHINCDIR}/ansi_stdlib.h fmtulong.o: ${BASHINCDIR}/chartypes.h fmtulong.o: ${BASHINCDIR}/stdc.h fmtulong.o: ${BASHINCDIR}/typemax.h fmtullong.o: ${topdir}/bashansi.h fmtullong.o: ${BASHINCDIR}/ansi_stdlib.h fmtullong.o: ${BASHINCDIR}/chartypes.h fmtullong.o: ${BASHINCDIR}/stdc.h fmtullong.o: ${BASHINCDIR}/typemax.h fmtumax.o: ${topdir}/bashansi.h fmtumax.o: ${BASHINCDIR}/ansi_stdlib.h fmtumax.o: ${BASHINCDIR}/chartypes.h fmtumax.o: ${BASHINCDIR}/stdc.h fmtumax.o: ${BASHINCDIR}/typemax.h xstrchr.o: ${topdir}/bashansi.h xstrchr.o: ${BASHINCDIR}/ansi_stdlib.h xstrchr.o: ${BASHINCDIR}/shmbutil.h --- NEW FILE: tmpfile.c --- /* * tmpfile.c - functions to create and safely open temp files for the shell. */ /* Copyright (C) 2000 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #include <bashtypes.h> #include <posixstat.h> #include <posixtime.h> #include <filecntl.h> #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #include <stdio.h> #include <errno.h> #include <shell.h> #ifndef errno extern int errno; #endif #define BASEOPENFLAGS (O_CREAT | O_TRUNC | O_EXCL) #define DEFAULT_TMPDIR "." /* bogus default, should be changed */ #define DEFAULT_NAMEROOT "shtmp" extern pid_t dollar_dollar_pid; static char *sys_tmpdir = (char *)NULL; static int ntmpfiles; static int tmpnamelen = -1; static unsigned long filenum = 1L; static char * get_sys_tmpdir () { struct stat sb; if (sys_tmpdir) return sys_tmpdir; #ifdef P_tmpdir sys_tmpdir = P_tmpdir; if (stat (sys_tmpdir, &sb) == 0) return sys_tmpdir; #endif sys_tmpdir = "/tmp"; if (stat (sys_tmpdir, &sb) == 0) return sys_tmpdir; sys_tmpdir = "/var/tmp"; if (stat (sys_tmpdir, &sb) == 0) return sys_tmpdir; sys_tmpdir = "/usr/tmp"; if (stat (sys_tmpdir, &sb) == 0) return sys_tmpdir; sys_tmpdir = DEFAULT_TMPDIR; return sys_tmpdir; } static char * get_tmpdir (flags) int flags; { char *tdir; tdir = (flags & MT_USETMPDIR) ? get_string_value ("TMPDIR") : (char *)NULL; if (tdir == 0) tdir = get_sys_tmpdir (); #if defined (HAVE_PATHCONF) && defined (_PC_NAME_MAX) if (tmpnamelen == -1) tmpnamelen = pathconf (tdir, _PC_NAME_MAX); #else tmpnamelen = 0; #endif return tdir; } char * sh_mktmpname (nameroot, flags) char *nameroot; int flags; { char *filename, *tdir, *lroot; struct stat sb; int r, tdlen; filename = (char *)xmalloc (PATH_MAX + 1); tdir = get_tmpdir (flags); tdlen = strlen (tdir); lroot = nameroot ? nameroot : DEFAULT_NAMEROOT; #ifdef USE_MKTEMP sprintf (filename, "%s/%s.XXXXXX", tdir, lroot); if (mktemp (filename) == 0) { free (filename); filename = NULL; } #else /* !USE_MKTEMP */ while (1) { filenum = (filenum << 1) ^ (unsigned long) time ((time_t *)0) ^ (unsigned long) dollar_dollar_pid ^ (unsigned long) ((flags & MT_USERANDOM) ? get_random_number () : ntmpfiles++); sprintf (filename, "%s/%s-%lu", tdir, lroot, filenum); if (tmpnamelen > 0 && tmpnamelen < 32) filename[tdlen + 1 + tmpnamelen] = '\0'; # ifdef HAVE_LSTAT r = lstat (filename, &sb); # else r = stat (filename, &sb); # endif if (r < 0 && errno == ENOENT) break; } #endif /* !USE_MKTEMP */ return filename; } int sh_mktmpfd (nameroot, flags, namep) char *nameroot; int flags; char **namep; { char *filename, *tdir, *lroot; int fd, tdlen; filename = (char *)xmalloc (PATH_MAX + 1); tdir = get_tmpdir (flags); tdlen = strlen (tdir); lroot = nameroot ? nameroot : DEFAULT_NAMEROOT; #ifdef USE_MKSTEMP sprintf (filename, "%s/%s.XXXXXX", tdir, lroot); fd = mkstemp (filename); if (fd < 0 || namep == 0) { free (filename); filename = NULL; } if (namep) *namep = filename; return fd; #else /* !USE_MKSTEMP */ do { filenum = (filenum << 1) ^ (unsigned long) time ((time_t *)0) ^ (unsigned long) dollar_dollar_pid ^ (unsigned long) ((flags & MT_USERANDOM) ? get_random_number () : ntmpfiles++); sprintf (filename, "%s/%s-%lu", tdir, lroot, filenum); if (tmpnamelen > 0 && tmpnamelen < 32) filename[tdlen + 1 + tmpnamelen] = '\0'; fd = open (filename, BASEOPENFLAGS | ((flags & MT_READWRITE) ? O_RDWR : O_WRONLY), 0600); } while (fd < 0 && errno == EEXIST); if (namep) *namep = filename; else free (filename); return fd; #endif /* !USE_MKSTEMP */ } FILE * sh_mktmpfp (nameroot, flags, namep) char *nameroot; int flags; char **namep; { int fd; FILE *fp; fd = sh_mktmpfd (nameroot, flags, namep); if (fd < 0) return ((FILE *)NULL); fp = fdopen (fd, (flags & MT_READWRITE) ? "w+" : "w"); if (fp == 0) close (fd); return fp; } --- NEW FILE: vprint.c --- /* vprint.c -- v[fs]printf() for 4.[23] BSD systems. */ /* Copyright (C) 1987,1989 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #if defined (USE_VFPRINTF_EMULATION) #include <stdio.h> #if !defined (NULL) # if defined (__STDC__) # define NULL ((void *)0) # else # define NULL 0x0 # endif /* __STDC__ */ #endif /* !NULL */ /* * Beware! Don't trust the value returned by either of these functions; it * seems that pre-4.3-tahoe implementations of _doprnt () return the first * argument, i.e. a char *. */ #include <varargs.h> int vfprintf (iop, fmt, ap) FILE *iop; char *fmt; va_list ap; { int len; char localbuf[BUFSIZ]; if (iop->_flag & _IONBF) { iop->_flag &= ~_IONBF; iop->_ptr = iop->_base = localbuf; len = _doprnt (fmt, ap, iop); (void) fflush (iop); iop->_flag |= _IONBF; iop->_base = NULL; iop->_bufsiz = 0; iop->_cnt = 0; } else len = _doprnt (fmt, ap, iop); return (ferror (iop) ? EOF : len); } /* * Ditto for vsprintf */ int vsprintf (str, fmt, ap) char *str, *fmt; va_list ap; { FILE f; int len; f._flag = _IOWRT|_IOSTRG; f._ptr = str; f._cnt = 32767; len = _doprnt (fmt, ap, &f); *f._ptr = 0; return (len); } #endif /* USE_VFPRINTF_EMULATION */ --- NEW FILE: zread.c --- /* Copyright (C) 1999-2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <config.h> #include <sys/types.h> #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #include <errno.h> #if !defined (errno) extern int errno; #endif #ifndef SEEK_CUR # define SEEK_CUR 1 #endif /* Read LEN bytes from FD into BUF. Retry the read on EINTR. Any other error causes the loop to break. */ ssize_t zread (fd, buf, len) int fd; char *buf; size_t len; { ssize_t r; while ((r = read (fd, buf, len)) < 0 && errno == EINTR) ; return r; } /* Read LEN bytes from FD into BUF. Retry the read on EINTR, up to three interrupts. Any other error causes the loop to break. */ #ifdef NUM_INTR # undef NUM_INTR #endif #define NUM_INTR 3 ssize_t zreadintr (fd, buf, len) int fd; char *buf; size_t len; { ssize_t r; int nintr; for (nintr = 0; ; ) { r = read (fd, buf, len); if (r >= 0) return r; if (r == -1 && errno == EINTR) { if (++nintr > NUM_INTR) return -1; continue; } return r; } } /* Read one character from FD and return it in CP. Return values are as in read(2). This does some local buffering to avoid many one-character calls to read(2), like those the `read' builtin performs. */ static char lbuf[128]; static size_t lind, lused; ssize_t zreadc (fd, cp) int fd; char *cp; { ssize_t nr; if (lind == lused || lused == 0) { nr = zread (fd, lbuf, sizeof (lbuf)); lind = 0; if (nr <= 0) { lused = 0; return nr; } lused = nr; } if (cp) *cp = lbuf[lind++]; return 1; } void zreset () { lind = lused = 0; } /* Sync the seek pointer for FD so that the kernel's idea of the last char read is the last char returned by zreadc. */ void zsyncfd (fd) int fd; { off_t off; off = lused - lind; if (off > 0) lseek (fd, -off, SEEK_CUR); lused = lind = 0; } --- NEW FILE: strftime.c --- /* * Modified slightly by Chet Ramey for inclusion in Bash */ /* * strftime.c * * Public-domain implementation of ISO C library routine. * * If you can't do prototypes, get GCC. * * The C99 standard now specifies just about all of the formats * that were additional in the earlier versions of this file. * * For extensions from SunOS, add SUNOS_EXT. * For extensions from HP/UX, add HPUX_EXT. * For VMS dates, add VMS_EXT. * For complete POSIX semantics, add POSIX_SEMANTICS. * * The code for %c, %x, and %X follows the C99 specification for * the "C" locale. * * This version ignores LOCALE information. * It also doesn't worry about multi-byte characters. * So there. * * This file is also shipped with GAWK (GNU Awk), gawk specific bits of * code are included if GAWK is defined. * * Arnold Robbins * January, February, March, 1991 * Updated March, April 1992 * Updated April, 1993 * Updated February, 1994 * Updated May, 1994 * Updated January, 1995 * Updated September, 1995 * Updated January, 1996 * Updated July, 1997 * Updated October, 1999 * Updated September, 2000 * * Fixes from ad...@el..., * February 1991, May 1992 * Fixes from Tor Lillqvist tm...@ti..., * May 1993 * Further fixes from ad...@el..., * February 1994 * %z code from ch...@ch..., * Applied September 1995 * %V code fixed (again) and %G, %g added, * January 1996 * %v code fixed, better configuration, * July 1997 * Moved to C99 specification. * September 2000 */ #include <config.h> #ifndef GAWK #include <stdio.h> #include <ctype.h> #include <time.h> #endif #if defined(TM_IN_SYS_TIME) #include <sys/types.h> #include <sys/time.h> #endif #include <stdlib.h> #include <string.h> /* defaults: season to taste */ #define SUNOS_EXT 1 /* stuff in SunOS strftime routine */ #define VMS_EXT 1 /* include %v for VMS date format */ #define HPUX_EXT 1 /* non-conflicting stuff in HP-UX date */ #ifndef GAWK #define POSIX_SEMANTICS 1 /* call tzset() if TZ changes */ #endif #undef strchr /* avoid AIX weirdness */ extern void tzset(void); static int weeknumber(const struct tm *timeptr, int firstweekday); static int iso8601wknum(const struct tm *timeptr); #ifdef __GNUC__ #define inline __inline__ #else #define inline /**/ #endif #define range(low, item, hi) max(low, min(item, hi)) #if !defined(OS2) && !defined(MSDOS) && defined(HAVE_TZNAME) extern char *tzname[2]; extern int daylight; #if defined(SOLARIS) || defined(mips) extern long int timezone, altzone; #else extern int timezone, altzone; #endif #endif #undef min /* just in case */ /* min --- return minimum of two numbers */ static inline int min(int a, int b) { return (a < b ? a : b); } #undef max /* also, just in case */ /* max --- return maximum of two numbers */ static inline int max(int a, int b) { return (a > b ? a : b); } /* strftime --- produce formatted time */ size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *timeptr) { char *endp = s + maxsize; char *start = s; auto char tbuf[100]; long off; int i, w, y; static short first = 1; #ifdef POSIX_SEMANTICS static char *savetz = NULL; static int savetzlen = 0; char *tz; #endif /* POSIX_SEMANTICS */ #ifndef HAVE_TM_ZONE #ifndef HAVE_TM_NAME #ifndef HAVE_TZNAME extern char *timezone(); struct timeval tv; struct timezone zone; #endif /* HAVE_TZNAME */ #endif /* HAVE_TM_NAME */ #endif /* HAVE_TM_ZONE */ /* various tables, useful in North America */ static const char *days_a[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", }; static const char *days_l[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", }; static const char *months_a[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; static const char *months_l[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", }; static const char *ampm[] = { "AM", "PM", }; if (s == NULL || format == NULL || timeptr == NULL || maxsize == 0) return 0; /* quick check if we even need to bother */ if (strchr(format, '%') == NULL && strlen(format) + 1 >= maxsize) return 0; #ifndef POSIX_SEMANTICS if (first) { tzset(); first = 0; } #else /* POSIX_SEMANTICS */ #if defined (SHELL) tz = get_string_value ("TZ"); #else tz = getenv("TZ"); #endif if (first) { if (tz != NULL) { int tzlen = strlen(tz); savetz = (char *) malloc(tzlen + 1); if (savetz != NULL) { savetzlen = tzlen + 1; strcpy(savetz, tz); } } tzset(); first = 0; } /* if we have a saved TZ, and it is different, recapture and reset */ if (tz && savetz && (tz[0] != savetz[0] || strcmp(tz, savetz) != 0)) { i = strlen(tz) + 1; if (i > savetzlen) { savetz = (char *) realloc(savetz, i); if (savetz) { savetzlen = i; strcpy(savetz, tz); } } else strcpy(savetz, tz); tzset(); } #endif /* POSIX_SEMANTICS */ for (; *format && s < endp - 1; format++) { tbuf[0] = '\0'; if (*format != '%') { *s++ = *format; continue; } again: switch (*++format) { case '\0': *s++ = '%'; goto out; case '%': *s++ = '%'; continue; case 'a': /* abbreviated weekday name */ if (timeptr->tm_wday < 0 || timeptr->tm_wday > 6) strcpy(tbuf, "?"); else strcpy(tbuf, days_a[timeptr->tm_wday]); break; case 'A': /* full weekday name */ if (timeptr->tm_wday < 0 || timeptr->tm_wday > 6) strcpy(tbuf, "?"); else strcpy(tbuf, days_l[timeptr->tm_wday]); break; case 'b': /* abbreviated month name */ short_month: if (timeptr->tm_mon < 0 || timeptr->tm_mon > 11) strcpy(tbuf, "?"); else strcpy(tbuf, months_a[timeptr->tm_mon]); break; case 'B': /* full month name */ if (timeptr->tm_mon < 0 || timeptr->tm_mon > 11) strcpy(tbuf, "?"); else strcpy(tbuf, months_l[timeptr->tm_mon]); break; case 'c': /* appropriate date and time representation */ /* * This used to be: * * strftime(tbuf, sizeof tbuf, "%a %b %e %H:%M:%S %Y", timeptr); * * Now, per the ISO 1999 C standard, it this: */ strftime(tbuf, sizeof tbuf, "%A %B %d %T %Y", timeptr); break; case 'C': century: sprintf(tbuf, "%02d", (timeptr->tm_year + 1900) / 100); break; case 'd': /* day of the month, 01 - 31 */ i = range(1, timeptr->tm_mday, 31); sprintf(tbuf, "%02d", i); break; case 'D': /* date as %m/%d/%y */ strftime(tbuf, sizeof tbuf, "%m/%d/%y", timeptr); break; case 'e': /* day of month, blank padded */ sprintf(tbuf, "%2d", range(1, timeptr->tm_mday, 31)); break; case 'E': /* POSIX (now C99) locale extensions, ignored for now */ goto again; case 'F': /* ISO 8601 date representation */ strftime(tbuf, sizeof tbuf, "%Y-%m-%d", timeptr); break; case 'g': case 'G': /* * Year of ISO week. * * If it's December but the ISO week number is one, * that week is in next year. * If it's January but the ISO week number is 52 or * 53, that week is in last year. * Otherwise, it's this year. */ w = iso8601wknum(timeptr); if (timeptr->tm_mon == 11 && w == 1) y = 1900 + timeptr->tm_year + 1; else if (timeptr->tm_mon == 0 && w >= 52) y = 1900 + timeptr->tm_year - 1; else y = 1900 + timeptr->tm_year; if (*format == 'G') sprintf(tbuf, "%d", y); else sprintf(tbuf, "%02d", y % 100); break; case 'h': /* abbreviated month name */ goto short_month; case 'H': /* hour, 24-hour clock, 00 - 23 */ i = range(0, timeptr->tm_hour, 23); sprintf(tbuf, "%02d", i); break; case 'I': /* hour, 12-hour clock, 01 - 12 */ i = range(0, timeptr->tm_hour, 23); if (i == 0) i = 12; else if (i > 12) i -= 12; sprintf(tbuf, "%02d", i); break; case 'j': /* day of the year, 001 - 366 */ sprintf(tbuf, "%03d", timeptr->tm_yday + 1); break; case 'm': /* month, 01 - 12 */ i = range(0, timeptr->tm_mon, 11); sprintf(tbuf, "%02d", i + 1); break; case 'M': /* minute, 00 - 59 */ i = range(0, timeptr->tm_min, 59); sprintf(tbuf, "%02d", i); break; case 'n': /* same as \n */ tbuf[0] = '\n'; tbuf[1] = '\0'; break; case 'O': /* POSIX (now C99) locale extensions, ignored for now */ goto again; case 'p': /* am or pm based on 12-hour clock */ i = range(0, timeptr->tm_hour, 23); if (i < 12) strcpy(tbuf, ampm[0]); else strcpy(tbuf, ampm[1]); break; case 'r': /* time as %I:%M:%S %p */ strftime(tbuf, sizeof tbuf, "%I:%M:%S %p", timeptr); break; case 'R': /* time as %H:%M */ strftime(tbuf, sizeof tbuf, "%H:%M", timeptr); break; #if defined(HAVE_MKTIME) || defined(GAWK) case 's': /* time as seconds since the Epoch */ { struct tm non_const_timeptr; non_const_timeptr = *timeptr; sprintf(tbuf, "%ld", mktime(& non_const_timeptr)); break; } #endif /* defined(HAVE_MKTIME) || defined(GAWK) */ case 'S': /* second, 00 - 60 */ i = range(0, timeptr->tm_sec, 60); sprintf(tbuf, "%02d", i); break; case 't': /* same as \t */ tbuf[0] = '\t'; tbuf[1] = '\0'; break; case 'T': /* time as %H:%M:%S */ the_time: strftime(tbuf, sizeof tbuf, "%H:%M:%S", timeptr); break; case 'u': /* ISO 8601: Weekday as a decimal number [1 (Monday) - 7] */ sprintf(tbuf, "%d", timeptr->tm_wday == 0 ? 7 : timeptr->tm_wday); break; case 'U': /* week of year, Sunday is first day of week */ sprintf(tbuf, "%02d", weeknumber(timeptr, 0)); break; case 'V': /* week of year according ISO 8601 */ sprintf(tbuf, "%02d", iso8601wknum(timeptr)); break; case 'w': /* weekday, Sunday == 0, 0 - 6 */ i = range(0, timeptr->tm_wday, 6); sprintf(tbuf, "%d", i); break; case 'W': /* week of year, Monday is first day of week */ sprintf(tbuf, "%02d", weeknumber(timeptr, 1)); break; case 'x': /* appropriate date representation */ strftime(tbuf, sizeof tbuf, "%A %B %d %Y", timeptr); break; case 'X': /* appropriate time representation */ goto the_time; break; case 'y': /* year without a century, 00 - 99 */ year: i = timeptr->tm_year % 100; sprintf(tbuf, "%02d", i); break; case 'Y': /* year with century */ fullyear: sprintf(tbuf, "%d", 1900 + timeptr->tm_year); break; /* * From: Chip Rosenthal <ch...@ch...> * Date: Sun, 19 Mar 1995 00:33:29 -0600 (CST) * * Warning: the %z [code] is implemented by inspecting the * timezone name conditional compile settings, and * inferring a method to get timezone offsets. I've tried * this code on a couple of machines, but I don't doubt * there is some system out there that won't like it. * Maybe the easiest thing to do would be to bracket this * with an #ifdef that can turn it off. The %z feature * would be an admittedly obscure one that most folks can * live without, but it would be a great help to those of * us that muck around with various message processors. */ case 'z': /* time zone offset east of GMT e.g. -0600 */ #ifdef HAVE_TM_NAME /* * Systems with tm_name probably have tm_tzadj as * secs west of GMT. Convert to mins east of GMT. */ off = -timeptr->tm_tzadj / 60; #else /* !HAVE_TM_NAME */ #ifdef HAVE_TM_ZONE /* * Systems with tm_zone probably have tm_gmtoff as * secs east of GMT. Convert to mins east of GMT. */ off = timeptr->tm_gmtoff / 60; #else /* !HAVE_TM_ZONE */ #if HAVE_TZNAME /* * Systems with tzname[] probably have timezone as * secs west of GMT. Convert to mins east of GMT. */ off = -(daylight ? timezone : altzone) / 60; #else /* !HAVE_TZNAME */ off = -zone.tz_minuteswest; #endif /* !HAVE_TZNAME */ #endif /* !HAVE_TM_ZONE */ #endif /* !HAVE_TM_NAME */ if (off < 0) { tbuf[0] = '-'; off = -off; } else { tbuf[0] = '+'; } sprintf(tbuf+1, "%02d%02d", off/60, off%60); break; case 'Z': /* time zone name or abbrevation */ #ifdef HAVE_TZNAME i = (daylight && timeptr->tm_isdst > 0); /* 0 or 1 */ strcpy(tbuf, tzname[i]); #else #ifdef HAVE_TM_ZONE strcpy(tbuf, timeptr->tm_zone); #else #ifdef HAVE_TM_NAME strcpy(tbuf, timeptr->tm_name); #else gettimeofday(& tv, & zone); strcpy(tbuf, timezone(zone.tz_minuteswest, timeptr->tm_isdst > 0)); #endif /* HAVE_TM_NAME */ #endif /* HAVE_TM_ZONE */ #endif /* HAVE_TZNAME */ break; #ifdef SUNOS_EXT case 'k': /* hour, 24-hour clock, blank pad */ sprintf(tbuf, "%2d", range(0, timeptr->tm_hour, 23)); break; case 'l': /* hour, 12-hour clock, 1 - 12, blank pad */ i = range(0, timeptr->tm_hour, 23); if (i == 0) i = 12; else if (i > 12) i -= 12; sprintf(tbuf, "%2d", i); break; #endif #ifdef HPUX_EXT case 'N': /* Emperor/Era name */ /* this is essentially the same as the century */ goto century; /* %C */ case 'o': /* Emperor/Era year */ goto year; /* %y */ #endif /* HPUX_EXT */ #ifdef VMS_EXT case 'v': /* date as dd-bbb-YYYY */ sprintf(tbuf, "%2d-%3.3s-%4d", range(1, timeptr->tm_mday, 31), months_a[range(0, timeptr->tm_mon, 11)], timeptr->tm_year + 1900); for (i = 3; i < 6; i++) if (islower(tbuf[i])) tbuf[i] = toupper(tbuf[i]); break; #endif default: tbuf[0] = '%'; tbuf[1] = *format; tbuf[2] = '\0'; break; } i = strlen(tbuf); if (i) { if (s + i < endp - 1) { strcpy(s, tbuf); s += i; } else return 0; } } out: if (s < endp && *format == '\0') { *s = '\0'; return (s - start); } else return 0; } /* isleap --- is a year a leap year? */ static int isleap(int year) { return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } /* iso8601wknum --- compute week number according to ISO 8601 */ static int iso8601wknum(const struct tm *timeptr) { /* * From 1003.2: * If the week (Monday to Sunday) containing January 1 * has four or more days in the new year, then it is week 1; * otherwise it is the highest numbered week of the previous * year (52 or 53), and the next week is week 1. * * ADR: This means if Jan 1 was Monday through Thursday, * it was week 1, otherwise week 52 or 53. * * XPG4 erroneously included POSIX.2 rationale text in the * main body of the standard. Thus it requires week 53. */ int weeknum, jan1day, diff; /* get week number, Monday as first day of the week */ weeknum = weeknumber(timeptr, 1); /* * With thanks and tip of the hatlo to tm...@ti... * * What day of the week does January 1 fall on? * We know that * (timeptr->tm_yday - jan1.tm_yday) MOD 7 == * (timeptr->tm_wday - jan1.tm_wday) MOD 7 * and that * jan1.tm_yday == 0 * and that * timeptr->tm_wday MOD 7 == timeptr->tm_wday * from which it follows that. . . */ jan1day = timeptr->tm_wday - (timeptr->tm_yday % 7); if (jan1day < 0) jan1day += 7; /* * If Jan 1 was a Monday through Thursday, it was in * week 1. Otherwise it was last year's highest week, which is * this year's week 0. * * What does that mean? * If Jan 1 was Monday, the week number is exactly right, it can * never be 0. * If it was Tuesday through Thursday, the weeknumber is one * less than it should be, so we add one. * Otherwise, Friday, Saturday or Sunday, the week number is * OK, but if it is 0, it needs to be 52 or 53. */ switch (jan1day) { case 1: /* Monday */ break; case 2: /* Tuesday */ case 3: /* Wednesday */ case 4: /* Thursday */ weeknum++; break; case 5: /* Friday */ case 6: /* Saturday */ case 0: /* Sunday */ if (weeknum == 0) { #ifdef USE... [truncated message content] |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:36
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/termcap/grot In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/termcap/grot Added Files: COPYING ChangeLog INSTALL Makefile.in NEWS README configure configure.in termcap.info termcap.info-1 termcap.info-2 termcap.info-3 termcap.info-4 termcap.texi texinfo.tex Log Message: Pristine source --- NEW FILE: termcap.texi --- \input texinfo @c -*-texinfo-*- @setfilename termcap.info @settitle The Termcap Library @smallbook @ifinfo This file documents the termcap library of the GNU system. Copyright (C) 1988 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. @ignore Permission is granted to process this file through TeX and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). [...3578 lines suppressed...] Flag: Teleray 1061; several strange characteristics. @end table @node Var Index, Cap Index, Summary, Top @unnumbered Variable and Function Index @printindex fn @node Cap Index, Index, Var Index, Top @unnumbered Capability Index @printindex ky @node Index, , Cap Index, Top @unnumbered Concept Index @printindex cp @contents @bye --- NEW FILE: termcap.info-1 --- This is Info file ./termcap.info, produced by Makeinfo-1.55 from the input file ./termcap.texi. This file documents the termcap library of the GNU system. Copyright (C) 1988 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a [...1075 lines suppressed...] the value of the capability. They are special only when the string value is processed by `tputs', `tparam' or `tgoto'. By contrast, `\' and `^' are considered part of the syntax for specifying the characters in the string. Let's look at the VT52 example again: dw|vt52|DEC vt52:\ :cr=^M:do=^J:nl=^J:bl=^G:\ :le=^H:bs:cd=\EJ:ce=\EK:cl=\EH\EJ:\ :cm=\EY%+ %+ :co#80:li#24:\ :nd=\EC:ta=^I:pt:sr=\EI:up=\EA:\ :ku=\EA:kd=\EB:kr=\EC:kl=\ED:kb=^H: Here we see the numeric-valued capabilities `co' and `li', the flags `bs' and `pt', and many string-valued capabilities. Most of the strings start with ESC represented as `\E'. The rest contain control characters represented using `^'. The meanings of the individual capabilities are defined elsewhere (*note Capabilities::.). --- NEW FILE: termcap.info-3 --- This is Info file ./termcap.info, produced by Makeinfo-1.55 from the input file ./termcap.texi. This file documents the termcap library of the GNU system. Copyright (C) 1988 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a [...1441 lines suppressed...] File: termcap.info, Node: Var Index, Next: Cap Index, Prev: Summary, Up: Top Variable and Function Index *************************** * Menu: * BC: tgoto. * ospeed: Output Padding. * PC: Output Padding. * tgetent: Find. * tgetflag: Interrogate. * tgetnum: Interrogate. * tgetstr: Interrogate. * tgoto: tgoto. * tparam: tparam. * tputs: Output Padding. * UP: tgoto. --- NEW FILE: termcap.info-2 --- This is Info file ./termcap.info, produced by Makeinfo-1.55 from the input file ./termcap.texi. This file documents the termcap library of the GNU system. Copyright (C) 1988 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation. File: termcap.info, Node: Naming, Next: Inheriting, Prev: Capability Format, Up: Data Base Terminal Type Name Conventions ============================== There are conventions for choosing names of terminal types. For one thing, all letters should be in lower case. The terminal type for a terminal in its most usual or most fundamental mode of operation should not have a hyphen in it. If the same terminal has other modes of operation which require different terminal descriptions, these variant descriptions are given names made by adding suffixes with hyphens. Such alternate descriptions are used for two reasons: * When the terminal has a switch that changes its behavior. Since the computer cannot tell how the switch is set, the user must tell the computer by choosing the appropriate terminal type name. For example, the VT-100 has a setup flag that controls whether the cursor wraps at the right margin. If this flag is set to "wrap", you must use the terminal type `vt100-am'. Otherwise you must use `vt100-nam'. Plain `vt100' is defined as a synonym for either `vt100-am' or `vt100-nam' depending on the preferences of the local site. The standard suffix `-am' stands for "automatic margins". * To give the user a choice in how to use the terminal. This is done when the terminal has a switch that the computer normally controls. For example, the Ann Arbor Ambassador can be configured with many screen sizes ranging from 20 to 60 lines. Fewer lines make bigger characters but more lines let you see more of what you are editing. As a result, users have different preferences. Therefore, termcap provides terminal types for many screen sizes. If you choose type `aaa-30', the terminal will be configured to use 30 lines; if you choose `aaa-48', 48 lines will be used, and so on. Here is a list of standard suffixes and their conventional meanings: `-w' Short for "wide". This is a mode that gives the terminal more columns than usual. This is normally a user option. `-am' "Automatic margins". This is an alternate description for use when the terminal's margin-wrap switch is on; it contains the `am' flag. The implication is that normally the switch is off and the usual description for the terminal says that the switch is off. `-nam' "No automatic margins". The opposite of `-am', this names an alternative description which lacks the `am' flag. This implies that the terminal is normally operated with the margin-wrap switch turned on, and the normal description of the terminal says so. `-na' "No arrows". This terminal description initializes the terminal to keep its arrow keys in local mode. This is a user option. `-rv' "Reverse video". This terminal description causes text output for normal video to appear as reverse, and text output for reverse video to come out as normal. Often this description differs from the usual one by interchanging the two strings which turn reverse video on and off. This is a user option; you can choose either the "reverse video" variant terminal type or the normal terminal type, and termcap will obey. `-s' "Status". Says to enable use of a status line which ordinary output does not touch (*note Status Line::.). Some terminals have a special line that is used only as a status line. For these terminals, there is no need for an `-s' variant; the status line commands should be defined by default. On other terminals, enabling a status line means removing one screen line from ordinary use and reducing the effective screen height. For these terminals, the user can choose the `-s' variant type to request use of a status line. `-NLINES' Says to operate with NLINES lines on the screen, for terminals such as the Ambassador which provide this as an option. Normally this is a user option; by choosing the terminal type, you control how many lines termcap will use. `-NPAGESp' Says that the terminal has NPAGES pages worth of screen memory, for terminals where this is a hardware option. `-unk' Says that description is not for direct use, but only for reference in `tc' capabilities. Such a description is a kind of subroutine, because it describes the common characteristics of several variant descriptions that would use other suffixes in place of `-unk'. File: termcap.info, Node: Inheriting, Next: Changing, Prev: Naming, Up: Data Base Inheriting from Related Descriptions ==================================== When two terminal descriptions are similar, their identical parts do not need to be given twice. Instead, one of the two can be defined in terms of the other, using the `tc' capability. We say that one description "refers to" the other, or "inherits from" the other. The `tc' capability must be the last one in the terminal description, and its value is a string which is the name of another terminal type which is referred to. For example, N9|aaa|ambassador|aaa-30|ann arbor ambassador/30 lines:\ :ti=\E[2J\E[30;0;0;30p:\ :te=\E[60;0;0;30p\E[30;1H\E[J:\ :li#30:tc=aaa-unk: defines the terminal type `aaa-30' (also known as plain `aaa') in terms of `aaa-unk', which defines everything about the Ambassador that is independent of screen height. The types `aaa-36', `aaa-48' and so on for other screen heights are likewise defined to inherit from `aaa-unk'. The capabilities overridden by `aaa-30' include `li', which says how many lines there are, and `ti' and `te', which configure the terminal to use that many lines. The effective terminal description for type `aaa' consists of the text shown above followed by the text of the description of `aaa-unk'. The `tc' capability is handled automatically by `tgetent', which finds the description thus referenced and combines the two descriptions (*note Find::.). Therefore, only the implementor of the terminal descriptions needs to think about using `tc'. Users and application programmers do not need to be concerned with it. Since the reference terminal description is used last, capabilities specified in the referring description override any specifications of the same capabilities in the reference description. The referring description can cancel out a capability without specifying any new value for it by means of a special trick. Write the capability in the referring description, with the character `@' after the capability name, as follows: NZ|aaa-30-nam|ann arbor ambassador/30 lines/no automatic-margins:\ :am@:tc=aaa-30: File: termcap.info, Node: Changing, Prev: Inheriting, Up: Data Base When Changes in the Data Base Take Effect ========================================= Each application program must read the terminal description from the data base, so a change in the data base is effective for all jobs started after the change is made. The change will usually have no effect on a job that have been in existence since before the change. The program probably read the terminal description once, when it was started, and is continuing to use what it read then. If the program does not have a feature for reexamining the data base, then you will need to run it again (probably killing the old job). If the description in use is coming from the `TERMCAP' environment variable, then the data base file is effectively overridden, and changes in it will have no effect until you change the `TERMCAP' variable as well. For example, some users' `.login' files automatically copy the terminal description into `TERMCAP' to speed startup of applications. If you have done this, you will need to change the `TERMCAP' variable to make the changed data base take effect. File: termcap.info, Node: Capabilities, Next: Summary, Prev: Data Base, Up: Top Definitions of the Terminal Capabilities **************************************** This section is divided into many subsections, each for one aspect of use of display terminals. For writing a display program, you usually need only check the subsections for the operations you want to use. For writing a terminal description, you must read each subsection and fill in the capabilities described there. String capabilities that are display commands may require numeric parameters (*note Parameters::.). Most such capabilities do not use parameters. When a capability requires parameters, this is explicitly stated at the beginning of its definition. In simple cases, the first or second sentence of the definition mentions all the parameters, in the order they should be given, using a name in upper case for each one. For example, the `rp' capability is a command that requires two parameters; its definition begins as follows: String of commands to output a graphic character C, repeated N times. In complex cases or when there are many parameters, they are described explicitly. When a capability is described as obsolete, this means that programs should not be written to look for it, but terminal descriptions should still be written to provide it. When a capability is described as very obsolete, this means that it should be omitted from terminal descriptions as well. * Menu: * Basic:: Basic characteristics. * Screen Size:: Screen size, and what happens when it changes. * Cursor Motion:: Various ways to move the cursor. * Wrapping:: What happens if you write a character in the last column. * Scrolling:: Pushing text up and down on the screen. * Windows:: Limiting the part of the window that output affects. * Clearing:: Erasing one or many lines. * Insdel Line:: Making new blank lines in mid-screen; deleting lines. * Insdel Char:: Inserting and deleting characters within a line. * Standout:: Highlighting some of the text. * Underlining:: Underlining some of the text. * Cursor Visibility:: Making the cursor more or less easy to spot. * Bell:: Attracts user's attention; not localized on the screen. * Keypad:: Recognizing when function keys or arrows are typed. * Meta Key:: META acts like an extra shift key. * Initialization:: Commands used to initialize or reset the terminal. * Pad Specs:: Info for the kernel on how much padding is needed. * Status Line:: A status line displays "background" information. * Half-Line:: Moving by half-lines, for superscripts and subscripts. * Printer:: Controlling auxiliary printers of display terminals. File: termcap.info, Node: Basic, Next: Screen Size, Up: Capabilities Basic Characteristics ===================== This section documents the capabilities that describe the basic and nature of the terminal, and also those that are relevant to the output of graphic characters. `os' Flag whose presence means that the terminal can overstrike. This means that outputting a graphic character does not erase whatever was present in the same character position before. The terminals that can overstrike include printing terminals, storage tubes (all obsolete nowadays), and many bit-map displays. `eo' Flag whose presence means that outputting a space erases a character position even if the terminal supports overstriking. If this flag is not present and overstriking is supported, output of a space has no effect except to move the cursor. (On terminals that do not support overstriking, you can always assume that outputting a space at a position erases whatever character was previously displayed there.) `gn' Flag whose presence means that this terminal type is a generic type which does not really describe any particular terminal. Generic types are intended for use as the default type assigned when the user connects to the system, with the intention that the user should specify what type he really has. One example of a generic type is the type `network'. Since the generic type cannot say how to do anything interesting with the terminal, termcap-using programs will always find that the terminal is too weak to be supported if the user has failed to specify a real terminal type in place of the generic one. The `gn' flag directs these programs to use a different error message: "You have not specified your real terminal type", rather than "Your terminal is not powerful enough to be used". `hc' Flag whose presence means this is a hardcopy terminal. `rp' String of commands to output a graphic character C, repeated N times. The first parameter value is the ASCII code for the desired character, and the second parameter is the number of times to repeat the character. Often this command requires padding proportional to the number of times the character is repeated. This effect can be had by using parameter arithmetic with `%'-sequences to compute the amount of padding, then generating the result as a number at the front of the string so that `tputs' will treat it as padding. `hz' Flag whose presence means that the ASCII character `~' cannot be output on this terminal because it is used for display commands. Programs handle this flag by checking all text to be output and replacing each `~' with some other character(s). If this is not done, the screen will be thoroughly garbled. The old Hazeltine terminals that required such treatment are probably very rare today, so you might as well not bother to support this flag. `CC' String whose presence means the terminal has a settable command character. The value of the string is the default command character (which is usually ESC). All the strings of commands in the terminal description should be written to use the default command character. If you are writing an application program that changes the command character, use the `CC' capability to figure out how to translate all the display commands to work with the new command character. Most programs have no reason to look at the `CC' capability. `xb' Flag whose presence identifies Superbee terminals which are unable to transmit the characters ESC and `Control-C'. Programs which support this flag are supposed to check the input for the code sequences sent by the F1 and F2 keys, and pretend that ESC or `Control-C' (respectively) had been read. But this flag is obsolete, and not worth supporting. File: termcap.info, Node: Screen Size, Next: Cursor Motion, Prev: Basic, Up: Capabilities Screen Size =========== A terminal description has two capabilities, `co' and `li', that describe the screen size in columns and lines. But there is more to the question of screen size than this. On some operating systems the "screen" is really a window and the effective width can vary. On some of these systems, `tgetnum' uses the actual width of the window to decide what value to return for the `co' capability, overriding what is actually written in the terminal description. On other systems, it is up to the application program to check the actual window width using a system call. For example, on BSD 4.3 systems, the system call `ioctl' with code `TIOCGWINSZ' will tell you the current screen size. On all window systems, termcap is powerless to advise the application program if the user resizes the window. Application programs must deal with this possibility in a system-dependent fashion. On some systems the C shell handles part of the problem by detecting changes in window size and setting the `TERMCAP' environment variable appropriately. This takes care of application programs that are started subsequently. It does not help application programs already running. On some systems, including BSD 4.3, all programs using a terminal get a signal named `SIGWINCH' whenever the screen size changes. Programs that use termcap should handle this signal by using `ioctl TIOCGWINSZ' to learn the new screen size. `co' Numeric value, the width of the screen in character positions. Even hardcopy terminals normally have a `co' capability. `li' Numeric value, the height of the screen in lines. File: termcap.info, Node: Cursor Motion, Next: Wrapping, Prev: Screen Size, Up: Capabilities Cursor Motion ============= Termcap assumes that the terminal has a "cursor", a spot on the screen where a visible mark is displayed, and that most display commands take effect at the position of the cursor. It follows that moving the cursor to a specified location is very important. There are many terminal capabilities for different cursor motion operations. A terminal description should define as many as possible, but most programs do not need to use most of them. One capability, `cm', moves the cursor to an arbitrary place on the screen; this by itself is sufficient for any application as long as there is no need to support hardcopy terminals or certain old, weak displays that have only relative motion commands. Use of other cursor motion capabilities is an optimization, enabling the program to output fewer characters in some common cases. If you plan to use the relative cursor motion commands in an application program, you must know what the starting cursor position is. To do this, you must keep track of the cursor position and update the records each time anything is output to the terminal, including graphic characters. In addition, it is necessary to know whether the terminal wraps after writing in the rightmost column. *Note Wrapping::. One other motion capability needs special mention: `nw' moves the cursor to the beginning of the following line, perhaps clearing all the starting line after the cursor, or perhaps not clearing at all. This capability is a least common denominator that is probably supported even by terminals that cannot do most other things such as `cm' or `do'. Even hardcopy terminals can support `nw'. `cm' String of commands to position the cursor at line L, column C. Both parameters are origin-zero, and are defined relative to the screen, not relative to display memory. All display terminals except a few very obsolete ones support `cm', so it is acceptable for an application program to refuse to operate on terminals lacking `cm'. `ho' String of commands to move the cursor to the upper left corner of the screen (this position is called the "home position"). In terminals where the upper left corner of the screen is not the same as the beginning of display memory, this command must go to the upper left corner of the screen, not the beginning of display memory. Every display terminal supports this capability, and many application programs refuse to operate if the `ho' capability is missing. `ll' String of commands to move the cursor to the lower left corner of the screen. On some terminals, moving up from home position does this, but programs should never assume that will work. Just output the `ll' string (if it is provided); if moving to home position and then moving up is the best way to get there, the `ll' command will do that. `cr' String of commands to move the cursor to the beginning of the line it is on. If this capability is not specified, many programs assume they can use the ASCII carriage return character for this. `le' String of commands to move the cursor left one column. Unless the `bw' flag capability is specified, the effect is undefined if the cursor is at the left margin; do not use this command there. If `bw' is present, this command may be used at the left margin, and it wraps the cursor to the last column of the preceding line. `nd' String of commands to move the cursor right one column. The effect is undefined if the cursor is at the right margin; do not use this command there, not even if `am' is present. `up' String of commands to move the cursor vertically up one line. The effect of sending this string when on the top line is undefined; programs should never use it that way. `do' String of commands to move the cursor vertically down one line. The effect of sending this string when on the bottom line is undefined; programs should never use it that way. Some programs do use `do' to scroll up one line if used at the bottom line, if `sf' is not defined but `sr' is. This is only to compensate for certain old, incorrect terminal descriptions. (In principle this might actually lead to incorrect behavior on other terminals, but that seems to happen rarely if ever.) But the proper solution is that the terminal description should define `sf' as well as `do' if the command is suitable for scrolling. The original idea was that this string would not contain a newline character and therefore could be used without disabling the kernel's usual habit of converting of newline into a carriage-return newline sequence. But many terminal descriptions do use newline in the `do' string, so this is not possible; a program which sends the `do' string must disable output conversion in the kernel (*note Initialize::.). `bw' Flag whose presence says that `le' may be used in column zero to move to the last column of the preceding line. If this flag is not present, `le' should not be used in column zero. `nw' String of commands to move the cursor to start of next line, possibly clearing rest of line (following the cursor) before moving. `DO', `UP', `LE', `RI' Strings of commands to move the cursor N lines down vertically, up vertically, or N columns left or right. Do not attempt to move past any edge of the screen with these commands; the effect of trying that is undefined. Only a few terminal descriptions provide these commands, and most programs do not use them. `CM' String of commands to position the cursor at line L, column C, relative to display memory. Both parameters are origin-zero. This capability is present only in terminals where there is a difference between screen-relative and memory-relative addressing, and not even in all such terminals. `ch' String of commands to position the cursor at column C in the same line it is on. This is a special case of `cm' in which the vertical position is not changed. The `ch' capability is provided only when it is faster to output than `cm' would be in this special case. Programs should not assume most display terminals have `ch'. `cv' String of commands to position the cursor at line L in the same column. This is a special case of `cm' in which the horizontal position is not changed. The `cv' capability is provided only when it is faster to output than `cm' would be in this special case. Programs should not assume most display terminals have `cv'. `sc' String of commands to make the terminal save the current cursor position. Only the last saved position can be used. If this capability is present, `rc' should be provided also. Most terminals have neither. `rc' String of commands to make the terminal restore the last saved cursor position. If this capability is present, `sc' should be provided also. Most terminals have neither. `ff' String of commands to advance to the next page, for a hardcopy terminal. `ta' String of commands to move the cursor right to the next hardware tab stop column. Missing if the terminal does not have any kind of hardware tabs. Do not send this command if the kernel's terminal modes say that the kernel is expanding tabs into spaces. `bt' String of commands to move the cursor left to the previous hardware tab stop column. Missing if the terminal has no such ability; many terminals do not. Do not send this command if the kernel's terminal modes say that the kernel is expanding tabs into spaces. The following obsolete capabilities should be included in terminal descriptions when appropriate, but should not be looked at by new programs. `nc' Flag whose presence means the terminal does not support the ASCII carriage return character as `cr'. This flag is needed because old programs assume, when the `cr' capability is missing, that ASCII carriage return can be used for the purpose. We use `nc' to tell the old programs that carriage return may not be used. New programs should not assume any default for `cr', so they need not look at `nc'. However, descriptions should contain `nc' whenever they do not contain `cr'. `xt' Flag whose presence means that the ASCII tab character may not be used for cursor motion. This flag exists because old programs assume, when the `ta' capability is missing, that ASCII tab can be used for the purpose. We use `xt' to tell the old programs not to use tab. New programs should not assume any default for `ta', so they need not look at `xt' in connection with cursor motion. Note that `xt' also has implications for standout mode (*note Standout::.). It is obsolete in regard to cursor motion but not in regard to standout. In fact, `xt' means that the terminal is a Teleray 1061. `bc' Very obsolete alternative name for the `le' capability. `bs' Flag whose presence means that the ASCII character backspace may be used to move the cursor left. Obsolete; look at `le' instead. `nl' Obsolete capability which is a string that can either be used to move the cursor down or to scroll. The same string must scroll when used on the bottom line and move the cursor when used on any other line. New programs should use `do' or `sf', and ignore `nl'. If there is no `nl' capability, some old programs assume they can use the newline character for this purpose. These programs follow a bad practice, but because they exist, it is still desirable to define the `nl' capability in a terminal description if the best way to move down is *not* a newline. File: termcap.info, Node: Wrapping, Next: Scrolling, Prev: Cursor Motion, Up: Capabilities Wrapping ======== "Wrapping" means moving the cursor from the right margin to the left margin of the following line. Some terminals wrap automatically when a graphic character is output in the last column, while others do not. Most application programs that use termcap need to know whether the terminal wraps. There are two special flag capabilities to describe what the terminal does when a graphic character is output in the last column. `am' Flag whose presence means that writing a character in the last column causes the cursor to wrap to the beginning of the next line. If `am' is not present, writing in the last column leaves the cursor at the place where the character was written. Writing in the last column of the last line should be avoided on terminals with `am', as it may or may not cause scrolling to occur (*note Scrolling::.). Scrolling is surely not what you would intend. If your program needs to check the `am' flag, then it also needs to check the `xn' flag which indicates that wrapping happens in a strange way. Many common terminals have the `xn' flag. `xn' Flag whose presence means that the cursor wraps in a strange way. At least two distinct kinds of strange behavior are known; the termcap data base does not contain anything to distinguish the two. On Concept-100 terminals, output in the last column wraps the cursor almost like an ordinary `am' terminal. But if the next thing output is a newline, it is ignored. DEC VT-100 terminals (when the wrap switch is on) do a different strange thing: the cursor wraps only if the next thing output is another graphic character. In fact, the wrap occurs when the following graphic character is received by the terminal, before the character is placed on the screen. On both of these terminals, after writing in the last column a following graphic character will be displayed in the first column of the following line. But the effect of relative cursor motion characters such as newline or backspace at such a time depends on the terminal. The effect of erase or scrolling commands also depends on the terminal. You can't assume anything about what they will do on a terminal that has `xn'. So, to be safe, you should never do these things at such a time on such a terminal. To be sure of reliable results on a terminal which has the `xn' flag, output a `cm' absolute positioning command after writing in the last column. Another safe thing to do is to output carriage-return newline, which will leave the cursor at the beginning of the following line. `LP' Flag whose presence means that it is safe to write in the last column of the last line without worrying about undesired scrolling. `LP' indicates the DEC flavor of `xn' strangeness. File: termcap.info, Node: Scrolling, Next: Windows, Prev: Wrapping, Up: Capabilities Scrolling ========= "Scrolling" means moving the contents of the screen up or down one or more lines. Moving the contents up is "forward scrolling"; moving them down is "reverse scrolling". Scrolling happens after each line of output during ordinary output on most display terminals. But in an application program that uses termcap for random-access output, scrolling happens only when explicitly requested with the commands in this section. Some terminals have a "scroll region" feature. This lets you limit the effect of scrolling to a specified range of lines. Lines outside the range are unaffected when scrolling happens. The scroll region feature is available if either `cs' or `cS' is present. `sf' String of commands to scroll the screen one line up, assuming it is output with the cursor at the beginning of the bottom line. `sr' String of commands to scroll the screen one line down, assuming it is output with the cursor at the beginning of the top line. `do' A few programs will try to use `do' to do the work of `sf'. This is not really correct--it is an attempt to compensate for the absence of a `sf' command in some old terminal descriptions. Since these terminal descriptions do define `sr', perhaps at one time the definition of `do' was different and it could be used for scrolling as well. But it isn't desirable to combine these two functions in one capability, since scrolling often requires more padding than simply moving the cursor down. Defining `sf' and `do' separately allows you to specify the padding properly. Also, all sources agree that `do' should not be relied on to do scrolling. So the best approach is to add `sf' capabilities to the descriptions of these terminals, copying the definition of `do' if that does scroll. `SF' String of commands to scroll the screen N lines up, assuming it is output with the cursor at the beginning of the bottom line. `SR' String of commands to scroll the screen N lines down, assuming it is output with the cursor at the beginning of the top line. `cs' String of commands to set the scroll region. This command takes two parameters, START and END, which are the line numbers (origin-zero) of the first line to include in the scroll region and of the last line to include in it. When a scroll region is set, scrolling is limited to the specified range of lines; lines outside the range are not affected by scroll commands. Do not try to move the cursor outside the scroll region. The region remains set until explicitly removed. To remove the scroll region, use another `cs' command specifying the full height of the screen. The cursor position is undefined after the `cs' command is set, so position the cursor with `cm' immediately afterward. `cS' String of commands to set the scroll region using parameters in different form. The effect is the same as if `cs' were used. Four parameters are required: 1. Total number of lines on the screen. 2. Number of lines above desired scroll region. 3. Number of lines below (outside of) desired scroll region. 4. Total number of lines on the screen, the same as the first parameter. This capability is a GNU extension that was invented to allow the Ann Arbor Ambassador's scroll-region command to be described; it could also be done by putting non-Unix `%'-sequences into a `cs' string, but that would have confused Unix programs that used the `cs' capability with the Unix termcap. Currently only GNU Emacs uses the `cS' capability. `ns' Flag which means that the terminal does not normally scroll for ordinary sequential output. For modern terminals, this means that outputting a newline in ordinary sequential output with the cursor on the bottom line wraps to the top line. For some obsolete terminals, other things may happen. The terminal may be able to scroll even if it does not normally do so. If the `sf' capability is provided, it can be used for scrolling regardless of `ns'. `da' Flag whose presence means that lines scrolled up off the top of the screen may come back if scrolling down is done subsequently. The `da' and `db' flags do not, strictly speaking, affect how to scroll. But programs that scroll usually need to clear the lines scrolled onto the screen, if these flags are present. `db' Flag whose presence means that lines scrolled down off the bottom of the screen may come back if scrolling up is done subsequently. `lm' Numeric value, the number of lines of display memory that the terminal has. A value of zero means that the terminal has more display memory than can fit on the screen, but no fixed number of lines. (The number of lines may depend on the amount of text in each line.) Any terminal description that defines `SF' should also define `sf'; likewise for `SR' and `sr'. However, many terminals can only scroll by one line at a time, so it is common to find `sf' and not `SF', or `sr' without `SR'. Therefore, all programs that use the scrolling facilities should be prepared to work with `sf' in the case that `SF' is absent, and likewise with `sr'. On the other hand, an application program that uses only `sf' and not `SF' is acceptable, though slow on some terminals. When outputting a scroll command with `tputs', the NLINES argument should be the total number of lines in the portion of the screen being scrolled. Very often these commands require padding proportional to this number of lines. *Note Padding::. File: termcap.info, Node: Windows, Next: Clearing, Prev: Scrolling, Up: Capabilities Windows ======= A "window", in termcap, is a rectangular portion of the screen to which all display operations are restricted. Wrapping, clearing, scrolling, insertion and deletion all operate as if the specified window were all the screen there was. `wi' String of commands to set the terminal output screen window. This string requires four parameters, all origin-zero: 1. The first line to include in the window. 2. The last line to include in the window. 3. The first column to include in the window. 4. The last column to include in the window. Most terminals do not support windows. File: termcap.info, Node: Clearing, Next: Insdel Line, Prev: Windows, Up: Capabilities Clearing Parts of the Screen ============================ There are several terminal capabilities for clearing parts of the screen to blank. All display terminals support the `cl' string, and most display terminals support all of these capabilities. `cl' String of commands to clear the entire screen and position the cursor at the upper left corner. `cd' String of commands to clear the line the cursor is on, and all the lines below it, down to the bottom of the screen. This command string should be used only with the cursor in column zero; their effect is undefined if the cursor is elsewhere. `ce' String of commands to clear from the cursor to the end of the current line. `ec' String of commands to clear N characters, starting with the character that the cursor is on. This command string is expected to leave the cursor position unchanged. The parameter N should never be large enough to reach past the right margin; the effect of such a large parameter would be undefined. Clear to end of line (`ce') is extremely important in programs that maintain an updating display. Nearly all display terminals support this operation, so it is acceptable for a an application program to refuse to work if `ce' is not present. However, if you do not want this limitation, you can accomplish clearing to end of line by outputting spaces until you reach the right margin. In order to do this, you must know the current horizontal position. Also, this technique assumes that writing a space will erase. But this happens to be true on all the display terminals that fail to support `ce'. File: termcap.info, Node: Insdel Line, Next: Insdel Char, Prev: Clearing, Up: Capabilities Insert/Delete Line ================== "Inserting a line" means creating a blank line in the middle of the screen, and pushing the existing lines of text apart. In fact, the lines above the insertion point do not change, while the lines below move down, and one is normally lost at the bottom of the screen. "Deleting a line" means causing the line to disappear from the screen, closing up the gap by moving the lines below it upward. A new line appears at the bottom of the screen. Usually this line is blank, but on terminals with the `db' flag it may be a line previously moved off the screen bottom by scrolling or line insertion. Insertion and deletion of lines is useful in programs that maintain an updating display some parts of which may get longer or shorter. They are also useful in editors for scrolling parts of the screen, and for redisplaying after lines of text are killed or inserted. Many terminals provide commands to insert or delete a single line at the cursor position. Some provide the ability to insert or delete several lines with one command, using the number of lines to insert or delete as a parameter. Always move the cursor to column zero before using any of these commands. `al' String of commands to insert a blank line before the line the cursor is on. The existing line, and all lines below it, are moved down. The last line in the screen (or in the scroll region, if one is set) disappears and in most circumstances is discarded. It may not be discarded if the `db' is present (*note Scrolling::.). The cursor must be at the left margin before this command is used. This command does not move the cursor. `dl' String of commands to delete the line the cursor is on. The following lines move up, and a blank line appears at the bottom of the screen (or bottom of the scroll region). If the terminal has the `db' flag, a nonblank line previously pushed off the screen bottom may reappear at the bottom. The cursor must be at the left margin before this command is used. This command does not move the cursor. `AL' String of commands to insert N blank lines before the line that the cursor is on. It is like `al' repeated N times, except that it is as fast as one `al'. `DL' String of commands to delete N lines starting with the line that the cursor is on. It is like `dl' repeated N times, except that it is as fast as one `dl'. Any terminal description that defines `AL' should also define `al'; likewise for `DL' and `dl'. However, many terminals can only insert or delete one line at a time, so it is common to find `al' and not `AL', or `dl' without `DL'. Therefore, all programs that use the insert and delete facilities should be prepared to work with `al' in the case that `AL' is absent, and likewise with `dl'. On the other hand, it is acceptable to write an application that uses only `al' and `dl' and does not look for `AL' or `DL' at all. If a terminal does not support line insertion and deletion directly, but does support a scroll region, the effect of insertion and deletion can be obtained with scrolling. However, it is up to the individual user program to check for this possibility and use the scrolling commands to get the desired result. It is fairly important to implement this alternate strategy, since it is the only way to get the effect of line insertion and deletion on the popular VT100 terminal. Insertion and deletion of lines is affected by the scroll region on terminals that have a settable scroll region. This is useful when it is desirable to move any few consecutive lines up or down by a few lines. *Note Scrolling::. The line pushed off the bottom of the screen is not lost if the terminal has the `db' flag capability; instead, it is pushed into display memory that does not appear on the screen. This is the same thing that happens when scrolling pushes a line off the bottom of the screen. Either reverse scrolling or deletion of a line can bring the apparently lost line back onto the bottom of the screen. If the terminal has the scroll region feature as well as `db', the pushed-out line really is lost if a scroll region is in effect. When outputting an insert or delete command with `tputs', the NLINES argument should be the total number of lines from the cursor to the bottom of the screen (or scroll region). Very often these commands require padding proportional to this number of lines. *Note Padding::. For `AL' and `DL' the NLINES argument should *not* depend on the number of lines inserted or deleted; only the total number of lines affected. This is because it is just as fast to insert two or N lines with `AL' as to insert one line with `al'. --- NEW FILE: termcap.info --- This is Info file ./termcap.info, produced by Makeinfo-1.55 from the input file ./termcap.texi. This file documents the termcap library of the GNU system. Copyright (C) 1988 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation. Indirect: termcap.info-1: 874 termcap.info-2: 47411 termcap.info-3: 90390 termcap.info-4: 138827 Tag Table: (Indirect) Node: Top874 Node: Introduction4105 Node: Library5832 Node: Preparation6851 Node: Find8034 Node: Interrogate11492 Node: Initialize16800 Node: Padding18440 Node: Why Pad19146 Node: Not Enough20768 Node: Describe Padding23336 Node: Output Padding24826 Node: Parameters28441 Node: Encode Parameters30101 Node: Using Parameters36185 Node: tparam36780 Node: tgoto38806 Node: Data Base41361 Node: Format42257 Node: Capability Format44346 Node: Naming47411 Node: Inheriting51980 Node: Changing54224 Node: Capabilities55388 Node: Basic58127 Node: Screen Size62180 Node: Cursor Motion63920 Node: Wrapping74062 Node: Scrolling77091 Node: Windows82980 Node: Clearing83714 Node: Insdel Line85478 Node: Insdel Char90390 Node: Standout100375 Node: Underlining109433 Node: Cursor Visibility111852 Node: Bell112600 Node: Keypad113149 Node: Meta Key117864 Node: Initialization118818 Node: Pad Specs121369 Node: Status Line123422 Node: Half-Line125306 Node: Printer126108 Node: Summary127787 Node: Var Index138114 Node: Cap Index138827 Node: Index145991 End Tag Table --- NEW FILE: termcap.info-4 --- This is Info file ./termcap.info, produced by Makeinfo-1.55 from the input file ./termcap.texi. This file documents the termcap library of the GNU system. Copyright (C) 1988 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation. File: termcap.info, Node: Cap Index, Next: Index, Prev: Var Index, Up: Top Capability Index **************** * Menu: * ae: Standout. * al: Insdel Line. * AL: Insdel Line. * am: Wrapping. * as: Standout. * bc: Cursor Motion. * bl: Bell. * bs: Cursor Motion. * bt: Cursor Motion. * bw: Cursor Motion. * CC: Basic. * cd: Clearing. * ce: Clearing. * ch: Cursor Motion. * cl: Clearing. * cm: Cursor Motion. * CM: Cursor Motion. * co: Screen Size. * cr: Cursor Motion. * cS: Scrolling. * cs: Scrolling. * ct: Initialization. * cv: Cursor Motion. * da: Scrolling. * dB: Pad Specs. * db: Scrolling. * dC: Pad Specs. * DC: Insdel Char. * dc: Insdel Char. * dF: Pad Specs. * dl: Insdel Line. * DL: Insdel Line. * dm: Insdel Char. * dN: Pad Specs. * do: Cursor Motion. * DO: Cursor Motion. * ds: Status Line. * dT: Pad Specs. * ec: Clearing. * ed: Insdel Char. * ei: Insdel Char. * eo: Basic. * es: Status Line. * ff: Cursor Motion. * fs: Status Line. * gn: Basic. * hc: Basic. * hd: Half-Line. * ho: Cursor Motion. * hs: Status Line. * hu: Half-Line. * hz: Basic. * i1: Initialization. * i3: Initialization. * IC: Insdel Char. * ic: Insdel Char. * if: Initialization. * im: Insdel Char. * in: Insdel Char. * ip: Insdel Char. * is: Initialization. * it: Initialization. * K1...K5: Keypad. * k1...k9: Keypad. * kA...kT: Keypad. * ka...ku: Keypad. * km: Meta Key. * l0...l9: Keypad. * le: Cursor Motion. * LE: Cursor Motion. * li: Screen Size. * ll: Cursor Motion. * lm: Scrolling. * LP: Wrapping. * mb: Standout. * md: Standout. * me: Standout. * mh: Standout. * mi: Insdel Char. * mk: Standout. * mm: Meta Key. * mo: Meta Key. * mp: Standout. * mr: Standout. * ms: Standout. * ms: Underlining. * nc: Cursor Motion. * nd: Cursor Motion. * NF: Initialization. * nl: Cursor Motion. * ns: Scrolling. * nw: Cursor Motion. * os: Basic. * pb: Pad Specs. * pc: Pad Specs. * pf: Printer. * pO: Printer. * po: Printer. * ps: Printer. * rc: Cursor Motion. * RI: Cursor Motion. * rp: Basic. * rs: Initialization. * sa: Standout. * sc: Cursor Motion. * se: Standout. * SF: Scrolling. * sf: Scrolling. * sg: Standout. * so: Standout. * SR: Scrolling. * sr: Scrolling. * st: Initialization. * ta: Cursor Motion. * te: Initialization. * ti: Initialization. * ts: Status Line. * uc: Underlining. * ue: Underlining. * ug: Underlining. * ul: Underlining. * up: Cursor Motion. * UP: Cursor Motion. * us: Underlining. * vb: Bell. * ve: Cursor Visibility. * vi: Cursor Visibility. * vs: Cursor Visibility. * wi: Windows. * ws: Status Line. * xb: Basic. * xn: Wrapping. * xs: Standout. * xt: Cursor Motion. * xt: Standout. File: termcap.info, Node: Index, Prev: Cap Index, Up: Top Concept Index ************* * Menu: * %: Encode Parameters. * appearance modes: Standout. * bell: Bell. * clearing the screen: Clearing. * command character: Basic. * cursor motion: Cursor Motion. * delete character: Insdel Char. * delete line: Insdel Line. * delete mode: Insdel Char. * description format: Format. * erasing: Clearing. * generic terminal type: Basic. * home position: Cursor Motion. * inheritance: Inheriting. * initialization: Initialization. * insert character: Insdel Char. * insert line: Insdel Line. * insert mode: Insdel Char. * line speed: Output Padding. * magic cookie: Standout. * meta key: Meta Key. * names of terminal types: Naming. * overstrike: Basic. * padding: Pad Specs. * padding: Padding. * parameters: Parameters. * printer: Printer. * repeat output: Basic. * reset: Initialization. * screen size: Screen Size. * screen size: Naming. * screen size: Screen Size. * scrolling: Scrolling. * standout: Standout. * st... [truncated message content] |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:35
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/examples/startup-files In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/examples/startup-files Added Files: Bash_aliases Bash_profile Bashrc.bfox README bash-profile bashrc Log Message: Pristine source --- NEW FILE: bashrc --- if [ -z "$PS1" ]; then return fi # bogus if [ -f /unix ] ; then alias ls='/bin/ls -CF' else alias ls='/bin/ls -F' fi alias ll='ls -l' alias dir='ls -ba' alias ss="ps -aux" alias dot='ls .[a-zA-Z0-9_]*' alias news="xterm -g 80x45 -e trn -e -S1 -N &" alias c="clear" alias m="more" alias j="jobs" # common misspellings alias mroe=more alias pdw=pwd hash -p /usr/bin/mail mail if [ -z "$HOST" ] ; then export HOST=${HOSTNAME} fi HISTIGNORE="[ ]*:&:bg:fg" psgrep() { ps -aux | grep $1 | grep -v grep } # # This is a little like `zap' from Kernighan and Pike # pskill() { local pid pid=$(ps -ax | grep $1 | grep -v grep | awk '{ print $1 }') echo -n "killing $1 (process $pid)..." kill -9 $pid echo "slaughtered." } term() { TERM=$1 export TERM tset } xtitle () { echo -n -e "\033]0;$*\007" } cd() { builtin cd "$@" && xtitle $HOST: $PWD } bold() { tput smso } unbold() { tput rmso } if [ -f /unix ] ; then clear() { tput clear } fi rot13() { if [ $# = 0 ] ; then tr "[a-m][n-z][A-M][N-Z]" "[n-z][a-m][N-Z][A-M]" else tr "[a-m][n-z][A-M][N-Z]" "[n-z][a-m][N-Z][A-M]" < $1 fi } watch() { if [ $# -ne 1 ] ; then tail -f nohup.out else tail -f $1 fi } # # Remote login passing all 8 bits (so meta key will work) # rl() { rlogin $* -8 } function setenv() { if [ $# -ne 2 ] ; then echo "setenv: Too few arguments" else export $1="$2" fi } function chmog() { if [ $# -ne 4 ] ; then echo "usage: chmog mode owner group file" return 1 else chmod $1 $4 chown $2 $4 chgrp $3 $4 fi } --- NEW FILE: bash-profile --- # This is the filename where your incoming mail arrives. MAIL=~/mbox MAILCHECK=30 HISTFILE=~/.history/history.$HOSTNAME PATH1=/usr/homes/chet/bin.$HOSTTYPE:/usr/local/bin/gnu: PATH2=/usr/local/bin:/usr/ucb:/bin:/usr/bin/X11:. PATH3=/usr/bin:/usr/new/bin:/usr/contrib/bin PATH=$PATH1:$PATH2:$PATH3 EDITOR=/usr/local/bin/ce VISUAL=/usr/local/bin/ce FCEDIT=/usr/local/bin/ce SHELL=${SHELL:-${BASH:-/bin/bash}} PAGER=/usr/local/bin/less LESS='-i -e -M -P%t?f%f :stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...' # # Bogus 1003.2 variables. This should really be in /etc/profile # LOGNAME=${USER-$(whoami)} TZ=US/Eastern export HOME VISUAL EDITOR MAIL SHELL PATH TERM export PAGER LESS TERMCAP HISTSIZE HISTFILE MAIL MAILCHECK LOGNAME TZ PS1="${HOSTNAME}\$ " PS2='> ' export PS1 PS2 umask 022 if [ -f /unix ] ; then stty intr ^c # bogus fi if [ -f ~/.bashrc ] ; then . ~/.bashrc fi --- NEW FILE: Bashrc.bfox --- # Bourne Again SHell init file. # # Files you make look like rw-rw-r umask 002 # Don't make useless coredump files. If you want a coredump, # say "ulimit -c unlimited" and then cause a segmentation fault. ulimit -c 0 # Sometimes, there are lots of places that one can find tex inputs. export TEXINPUTS=.:$HOME/bin:/usr/lib/tex/inputs:/usr/local/lib/tex/inputs # Where's the Gnu stuff at? GNU=/usr/gnu/bin X11=/usr/bin/X11 UTIL_PATH=$GNU:$X11 STANDARD_PATH=/usr/local/bin:/usr/ucb:/bin:/usr/bin:/usr/etc:/etc:/usr/games if [ -d $HOME/bin/$HOSTTYPE ]; then MY_PATH=$HOME/bin/$HOSTTYPE fi if [ -d $HOME/bin ]; then MY_PATH=$MY_PATH:$HOME/bin fi if [ -d /usr/hosts ]; then STANDARD_PATH=$STANDARD_PATH:/usr/hosts fi PATH=.:$MY_PATH:$UTIL_PATH:$STANDARD_PATH # If not running interactively, then return if [ -z "$PS1" ]; then return fi # Set ignoreeof if you don't want EOF as the sole input to the shell to # immediately signal a quit condition. This only happens at the start # of a line if the line is empty, and you haven't just deleted a character # with C-d. I turn this on in ~/.bash_profile so that only login shells # have the right to be obnoxious. # set -o ignoreeof # Set auto_resume if you want to resume on "emacs", as well as on # "%emacs". auto_resume=exact # Set notify if you want to be asynchronously notified about background # job completion. set -o notify # Make it so that failed `exec' commands don't flush this shell. shopt -s execfail if [ -z "$LOGIN_SHELL" ]; then PS1="\u@\h\$ " fi HISTSIZE=256 MAILCHECK=60 # A couple of default aliases. alias j='jobs -l' alias po=popd alias pu=pushd alias ls='ls -F' [ -f ~/.bash_aliases ] && . ~/.bash_aliases --- NEW FILE: Bash_aliases --- # Some useful aliases. alias texclean='rm -f *.toc *.aux *.log *.cp *.fn *.tp *.vr *.pg *.ky' alias clean='echo -n "Really clean this directory?"; read yorn; if test "$yorn" = "y"; then rm -f \#* *~ .*~ *.bak .*.bak *.tmp .*.tmp core a.out; echo "Cleaned."; else echo "Not cleaned."; fi' alias h='history' alias j="jobs -l" alias l="ls -l " alias ll="ls -l" alias ls="ls -F" alias pu="pushd" alias po="popd" # # Csh compatability: # alias unsetenv=unset function setenv () { export $1="$2" } # Function which adds an alias to the current shell and to # the ~/.bash_aliases file. add-alias () { local name=$1 value="$2" echo alias $name=\'$value\' >>~/.bash_aliases eval alias $name=\'$value\' alias $name } # "repeat" command. Like: # # repeat 10 echo foo repeat () { local count="$1" i; shift; for i in $(seq 1 "$count"); do eval "$@"; done } # Subfunction needed by `repeat'. seq () { local lower upper output; lower=$1 upper=$2; if [ $lower -ge $upper ]; then return; fi while [ $lower -le $upper ]; do echo -n "$lower " lower=$(($lower + 1)) done echo "$lower" } --- NEW FILE: README --- Some sample startup files. The ones starting with capital letters are originally from Brian Fox. The ones starting with lowercase letters are from Chet Ramey. They will require changes for your environment. --- NEW FILE: Bash_profile --- # Startup file for bash login shells. # default_dir=/usr/local/lib/ if [ -n "$PS1" ]; then PS1='\u@\h(\#)\$ ' IGNOREEOF=3 fi LOGIN_SHELL=true # If the user has her own init file, then use that one, else use the # canonical one. if [ -f ~/.bashrc ]; then . ~/.bashrc elif [ -f ${default_dir}Bashrc ]; then . ${default_dir}Bashrc; fi |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:35
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/doc Added Files: FAQ INTRO Makefile.in README article.ms bash.1 bashbug.1 bashref.info bashref.texi builtins.1 htmlpost.sh rbash.1 texinfo.tex Log Message: Pristine source --- NEW FILE: FAQ --- This is the Bash FAQ, version 3.20, for Bash version 2.05b. This document contains a set of frequently-asked questions concerning Bash, the GNU Bourne-Again Shell. Bash is a freely-available command interpreter with advanced features for both interactive use and shell programming. Another good source of basic information about shells is the collection of FAQ articles periodically posted to comp.unix.shell. Questions and comments concerning this document should be sent to ch...@po.... This document is available for anonymous FTP with the URL ftp://ftp.cwru.edu/pub/bash/FAQ The Bash home page is http://cnswww.cns.cwru.edu/~chet/bash/bashtop.html [...1671 lines suppressed...] a better loadable interface to perl with access to the shell builtins and variables (contributions gratefully accepted) ksh93-like `nameref' variables ksh93-like `+=' variable assignment operator ksh93-like `xx.yy' variables (including some of the .sh.* variables) and associated disipline functions Some of the new ksh93 pattern matching operators, like backreferencing H5) When will the next release appear? The next version will appear sometime in 2002. Never make predictions. This document is Copyright 1995-2002 by Chester Ramey. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, and distribute this document for any purpose, provided that the above copyright notice appears in all copies of this document and that the contents of this document remain unaltered. --- NEW FILE: builtins.1 --- .\" This is a hack to force bash builtins into the whatis database .\" and to get the list of builtins to come up with the man command. .TH BASH_BUILTINS 1 "2001 November 27" "GNU Bash-2.05a" .SH NAME bash, :, ., [, alias, bg, bind, break, builtin, cd, command, compgen, complete, continue, declare, dirs, disown, echo, enable, eval, exec, exit, export, fc, fg, getopts, hash, help, history, jobs, kill, let, local, logout, popd, printf, pushd, pwd, read, readonly, return, set, shift, shopt, source, suspend, test, times, trap, type, typeset, ulimit, umask, unalias, unset, wait \- bash built-in commands, see \fBbash\fR(1) .SH BASH BUILTIN COMMANDS .nr zZ 1 .so bash.1 .SH SEE ALSO bash(1), sh(1) --- NEW FILE: Makefile.in --- # This Makefile is for the Bash/documentation directory -*- text -*-. # # Copyright (C) 1996 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. # SHELL = @MAKE_SHELL@ RM = rm -f topdir = @top_srcdir@ srcdir = @srcdir@ VPATH = .:@srcdir@ prefix = @prefix@ exec_prefix = @exec_prefix@ infodir = @infodir@ # set this to a directory name to have the HTML files installed htmldir = @htmldir@ # Support an alternate destination root directory for package building DESTDIR = mandir = @mandir@ manpfx = man man1ext = .1 man1dir = $(mandir)/$(manpfx)1 man3ext = .3 man3dir = $(mandir)/$(manpfx)3 INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ BUILD_DIR = @BUILD_DIR@ # bad style RL_LIBDIR = $(topdir)/lib/readline # unused TEXINDEX = texindex TEX = tex MAKEINFO = makeinfo TEXI2DVI = ${topdir}/support/texi2dvi TEXI2HTML = ${topdir}/support/texi2html MAN2HTML = ${BUILD_DIR}/support/man2html HTMLPOST = ${srcdir}/htmlpost.sh QUIETPS = #set this to -q to shut up dvips PAPERSIZE = letter # change to a4 for A4-size paper PSDPI = 300 # could be 600 if you like DVIPS = dvips -D ${PSDPI} $(QUIETPS) -t ${PAPERSIZE} -o $@ # tricky TEXINPUTDIR = $(RL_LIBDIR)/doc # These tools might not be available; they're not required DVIPDF = dvipdfm -o $@ -p ${PAPERSIZE} PSPDF = gs -sPAPERSIZE=${PAPERSIZE} -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -sOutputFile=$@ MKDIRS = ${topdir}/support/mkdirs # This should be a program that converts troff to an ascii-readable format NROFF = groff -Tascii # This should be a program that converts troff to postscript GROFF = groff HSUSER = $(RL_LIBDIR)/doc/hsuser.texinfo RLUSER = $(RL_LIBDIR)/doc/rluser.texinfo .SUFFIXES: .0 .1 .3 .ms .ps .txt .dvi .html .pdf .1.ps: $(RM) $@ -${GROFF} -man $< > $@ .1.0: $(RM) $@ -${NROFF} -man $< > $@ .1.html: $(RM) $@ -${MAN2HTML} $< | ${HTMLPOST} > $@ .ms.ps: $(RM) $@ -${GROFF} -ms $< > $@ .ms.txt: $(RM) $@ -${NROFF} -ms $< > $@ .3.ps: $(RM) $@ -${GROFF} -man $< > $@ .3.0: $(RM) $@ -${NROFF} -man $< > $@ .3.html: $(RM) $@ -${MAN2HTML} $< > $@ .ps.pdf: $(RM) $@ -${PSPDF} $< .dvi.pdf: $(RM) $@ -${DVIPDF} $< all: ps info dvi text html nodvi: ps info text html PSFILES = bash.ps bashbug.ps article.ps builtins.ps rbash.ps DVIFILES = bashref.dvi bashref.ps INFOFILES = bashref.info MAN0FILES = bash.0 bashbug.0 builtins.0 rbash.0 HTMLFILES = bashref.html bash.html PDFFILES = bash.pdf bashref.pdf article.pdf rose94.pdf ps: ${PSFILES} dvi: ${DVIFILES} info: ${INFOFILES} text: ${MAN0FILES} html: ${HTMLFILES} pdf: ${PDFFILES} bashref.dvi: $(srcdir)/bashref.texi $(HSUSER) $(RLUSER) TEXINPUTS=.:$(TEXINPUTDIR):$$TEXINPUTS $(TEXI2DVI) $(srcdir)/bashref.texi bashref.ps: bashref.dvi $(RM) $@ $(DVIPS) bashref.dvi bashref.info: $(srcdir)/bashref.texi $(HSUSER) $(RLUSER) $(MAKEINFO) --no-split -I$(TEXINPUTDIR) $(srcdir)/bashref.texi bashref.html: bashref.texi $(HSUSER) $(RLUSER) $(TEXI2HTML) -menu -monolithic -I $(TEXINPUTDIR) $(srcdir)/bashref.texi new-bashref.dvi: $(srcdir)/new-bashref.texi $(HSUSER) $(RLUSER) TEXINPUTS=.:$(TEXINPUTDIR):$$TEXINPUTS $(TEXI2DVI) $(srcdir)/new-bashref.texi new-bashref.ps: new-bashref.dvi $(RM) $@ $(DVIPS) new-bashref.dvi new-bashref.info: $(srcdir)/new-bashref.texi $(HSUSER) $(RLUSER) $(MAKEINFO) --no-split -I$(TEXINPUTDIR) $(srcdir)/new-bashref.texi #bash.dvi: bash.texinfo $(HSUSER) $(RLUSER) # TEXINPUTS=.:$(TEXINPUTDIR):$$TEXINPUTS $(TEXI2DVI) bash.texinfo # #bashman.ps: bash.dvi # $(RM) $@ # $(DVIPS) bash.dvi bash.txt: bash.1 bash.ps: bash.1 bash.html: bash.1 $(MAN2HTML) bashbug.ps: bashbug.1 builtins.ps: builtins.1 bash.1 rbash.ps: rbash.1 bash.1 bash.0: bash.1 bashbug.0: bashbug.1 builtins.0: builtins.1 bash.1 rbash.0: rbash.1 bash.1 article.ps: article.ms article.pdf: article.ps bashref.pdf: bashref.dvi bash.pdf: bash.ps rose94.pdf: rose94.ps $(MAN2HTML): ${topdir}/support/man2html.c -( cd ${BUILD_DIR}/support ; ${MAKE} ${MFLAGS} man2html) clean: $(RM) *.aux *.bak *.cp *.fn *.ky *.log *.pg *.toc *.tp *.vr *.cps \ *.pgs *.bt *.bts *.rw *.rws *.fns *.kys *.tps *.vrs *.o ${RM} core *.core mostlyclean: clean $(RM) Makefile distclean: clean maybe-clean $(RM) Makefile maintainer-clean: clean ${RM} ${PSFILES} ${DVIFILES} ${INFOFILES} ${MAN0FILES} ${HTMLFILES} ${RM} ${CREATED_FAQ} $(RM) Makefile maybe-clean: -if test "X$(topdir)" != "X$(BUILD_DIR)"; then \ $(RM) ${PSFILES} ${DVIFILES} ${INFOFILES} ${MAN0FILES} ${HTMLFILES}; \ fi installdirs: -test -d $(man1dir) || $(SHELL) ${MKDIRS} $(DESTDIR)$(man1dir) -test -d $(infodir) || $(SHELL) ${MKDIRS} $(DESTDIR)$(infodir) -if test -n "$(htmldir)" ; then \ test -d $(htmldir) || $(SHELL) ${MKDIRS} $(DESTDIR)$(htmldir) ; \ fi install: info installdirs -$(INSTALL_DATA) $(srcdir)/bash.1 $(DESTDIR)$(man1dir)/bash${man1ext} -$(INSTALL_DATA) $(srcdir)/bashbug.1 $(DESTDIR)$(man1dir)/bashbug${man1ext} # uncomment the next line to install the builtins man page # -$(INSTALL_DATA) $(srcdir)/builtins.1 $(DESTDIR)$(man1dir)/bash_builtins${man1ext} -$(INSTALL_DATA) $(srcdir)/bashref.info $(DESTDIR)$(infodir)/bash.info # run install-info if it is present to update the info directory if $(SHELL) -c 'install-info --version' >/dev/null 2>&1; then \ install-info --dir-file=$(DESTDIR)$(infodir)/dir $(DESTDIR)$(infodir)/bash.info; \ else true; fi # if htmldir is set, install the html files into that directory -if test -n "${htmldir}" ; then \ $(INSTALL_DATA) $(srcdir)/bash.html $(DESTDIR)$(htmldir) ; \ $(INSTALL_DATA) $(srcdir)/bashref.html $(DESTDIR)$(htmldir) ; \ fi uninstall: -$(RM) $(DESTDIR)$(man1dir)/bash${man1ext} $(DESTDIR)$(man1dir)/bashbug${man1ext} $(RM) $(DESTDIR)$(infodir)/bash.info -if test -n "$(htmldir)" ; then \ $(RM) $(DESTDIR)$(htmldir)/bash.html ; \ $(RM) $(DESTDIR)$(htmldir)/bashref.html ; \ fi # for use by chet CREATED_FAQ = faq.news faq.news2 faq.mail faq.version faq: ${CREATED_FAQ} faq.version: FAQ.version FAQ sh mkfaqvers FAQ.version > $@ faq.headers.mail: FAQ.headers.mail FAQ sh mkfaqvers FAQ.headers.mail > $@ faq.headers.news: FAQ.headers.news FAQ sh mkfaqvers FAQ.headers.news > $@ faq.headers.news2: FAQ.headers.news2 FAQ sh mkfaqvers FAQ.headers.news2 > $@ faq.news: FAQ faq.headers.news faq.version $(RM) $@ cat faq.headers.news faq.version FAQ > $@ faq.news2: FAQ faq.headers.news2 faq.version $(RM) $@ cat faq.headers.news2 faq.version FAQ > $@ faq.mail: FAQ faq.headers.mail faq.version $(RM) $@ cat faq.headers.mail faq.version FAQ > $@ inst: bashref.texi $(SHELL) ./mkinstall cmp -s INSTALL ../INSTALL || mv INSTALL ../INSTALL $(RM) INSTALL posix: bashref.texi $(SHELL) ./mkposix cmp -s POSIX ../POSIX || mv POSIX ../POSIX $(RM) POSIX rbash: bashref.texi $(SH) ./mkrbash cmp -s RBASH ../RBASH || mv RBASH ../RBASH $(RM) RBASH xdist: inst posix rbash --- NEW FILE: texinfo.tex --- % texinfo.tex -- TeX macros to handle Texinfo files. % % Load plain if necessary, i.e., if running under initex. \expandafter\ifx\csname fmtname\endcsname\relax\input plain\fi % \def\texinfoversion{1999-09-25.10} % % Copyright (C) 1985, 86, 88, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 % Free Software Foundation, Inc. % % This texinfo.tex file is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License as % published by the Free Software Foundation; either version 2, or (at % your option) any later version. % % This texinfo.tex file is distributed in the hope that it will be % useful, but WITHOUT ANY WARRANTY; without even the implied warranty % of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. [...5953 lines suppressed...] % Say @foo, not \foo, in error messages. @escapechar = `@@ % These look ok in all fonts, so just make them not special. @catcode`@& = @other @catcode`@# = @other @catcode`@% = @other @c Set initial fonts. @textfonts @rm @c Local variables: @c eval: (add-hook 'write-file-hooks 'time-stamp) @c page-delimiter: "^\\\\message" @c time-stamp-start: "def\\\\texinfoversion{" @c time-stamp-format: "%:y-%02m-%02d.%02H" @c time-stamp-end: "}" @c End: --- NEW FILE: article.ms --- .de SE \" start example .sp .5 .RS .ft CR .nf .. .de EE \" end example .fi .sp .5 .RE .ft R .. .TL Bash \- The GNU shell* .AU Chet Ramey Case Western Reserve University ch...@po... .FS [...1075 lines suppressed...] are included, and a \*Qminimal\*U configuration, which omits job control, aliases, history and command line editing, the directory stack and .B pushd/popd/dirs, process substitution, prompt string special character decoding, and the .I select construct. This minimal version is designed to be a drop-in replacement for the traditional \s-1UNIX\s+1 /bin/sh, and is included as the Linux /bin/sh in several packagings. .NH 1 Conclusion .PP Bash is a worthy successor to sh. It is sufficiently portable to run on nearly every version of \s-1UNIX\s+1 from 4.3 BSD to SVR4.2, and several \s-1UNIX\s+1 workalikes. It is robust enough to replace sh on most of those systems, and provides more functionality. It has several thousand regular users, and their feedback has helped to make it as good as it is today \- a testament to the benefits of free software. --- NEW FILE: htmlpost.sh --- #! /bin/sh # # Some of these should really be done by man2html # # The ~/xxx links don't really work -- netscape doesn't expand the home # directory of the user running navigator # sed -e 's|<B>gnu.bash.bug</B>|<A HREF="news:gnu.bash.bug">gnu.bash.bug</A>|g' \ -e 's|<I>/bin/bash</I>|<A HREF="file:/bin/bash"><I>/bin/bash</I></A>|g' \ -e 's|<I>/etc/profile</I>|<A HREF="file:/etc/profile"><I>/etc/profile</I></A>|g' \ -e 's|<I>~/.bash_profile</I>|<A HREF="file:~/.bash_profile"><I>~/.bash_profile</I></A>|g' \ -e 's|<I>~/.bash_login</I>|<A HREF="file:~/.bash_login"><I>~/.bash_login</I></A>|g' \ -e 's|<I>~/.profile</I>|<A HREF="file:~/.profile"><I>~/.profile</I></A>|g' \ -e 's|<I>~/.bashrc</I>|<A HREF="file:~/.bashrc"><I>~/.bashrc</I></A>|g' \ -e 's|<I>~/.bash_logout</I>|<A HREF="file:~/.bash_logout"><I>~/.bash_logout</I></A>|g' \ -e 's|<I>~/.bash_history</I>|<A HREF="file:~/.bash_history"><I>~/.bash_history</I></A>|g' \ -e 's|<I>~/.inputrc</I>|<A HREF="file:~/.inputrc"><I>~/.inputrc</I></A>|g' \ -e 's|<I>/etc/inputrc</I>|<A HREF="file:/etc/inputrc"><I>/etc/inputrc</I></A>|g' --- NEW FILE: bashbug.1 --- .TH BASHBUG 1 "1998 July 30" GNU .SH NAME bashbug \- report a bug in bash .SH SYNOPSIS \fBbashbug\fP [\fIaddress\fP] .SH DESCRIPTION .B bashbug is a shell script to help the user compose and mail bug reports concerning bash in a standard format. .B bashbug invokes the editor specified by the environment variable .SM .B EDITOR on a temporary copy of the bug report format outline. The user must fill in the appropriate fields and exit the editor. .B bashbug then mails the completed report to \fIb...@gn...\fP, or \fIaddress\fP. If the report cannot be mailed, it is saved in the file \fIdead.bashbug\fP in the invoking user's home directory. .PP The bug report format outline consists of several sections. The first section provides information about the machine, operating system, the bash version, and the compilation environment. The second section should be filled in with a description of the bug. The third section should be a description of how to reproduce the bug. The optional fourth section is for a proposed fix. Fixes are encouraged. .SH ENVIRONMENT .B bashbug will utilize the following environment variables if they exist: .TP .B EDITOR Specifies the preferred editor. If .SM .B EDITOR is not set, .B bashbug defaults to .BR emacs . .TP .B HOME Directory in which the failed bug report is saved if the mail fails. --- NEW FILE: rbash.1 --- .TH RBASH 1 "1999 Nov 29" GNU .SH NAME rbash \- restricted bash, see \fBbash\fR(1) .SH RESTRICTED SHELL .nr zY 1 .so bash.1 .SH SEE ALSO bash(1) --- NEW FILE: bashref.info --- This is bashref.info, produced by makeinfo version 4.1 from /usr/homes/chet/src/bash/src/doc/bashref.texi. INFO-DIR-SECTION Utilities START-INFO-DIR-ENTRY * Bash: (bash). The GNU Bourne-Again SHell. END-INFO-DIR-ENTRY This text is a brief description of the features that are present in the Bash shell. This is Edition 2.5b, last updated 15 July 2002, of `The GNU Bash Reference Manual', for `Bash', Version 2.05b. Copyright (C) 1991-2002 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice [...8454 lines suppressed...] Node: Word Designators279653 Node: Modifiers281282 Node: Installing Bash282599 Node: Basic Installation283741 Node: Compilers and Options286426 Node: Compiling For Multiple Architectures287160 Node: Installation Names288817 Node: Specifying the System Type289628 Node: Sharing Defaults290337 Node: Operation Controls291002 Node: Optional Features291953 Node: Reporting Bugs299895 Node: Major Differences From The Bourne Shell300992 Node: Builtin Index315476 Node: Reserved Word Index319067 Node: Variable Index320543 Node: Function Index326841 Node: Concept Index331391 End Tag Table --- NEW FILE: INTRO --- BASH - The Bourne-Again Shell Bash is the shell, or command language interpreter, that will appear in the GNU operating system. Bash is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard. It offers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification. Bash is quite portable. It uses a configuration system that discovers characteristics of the compilation platform at build time, and may therefore be built on nearly every version of UNIX. Ports to UNIX-like systems such as QNX and Minix and to non-UNIX systems such as OS/2, Windows 95, and Windows NT are available. Bash includes the following features: Editing and Completion Bash offers a command-line editing facility which permits users to edit command lines using familiar emacs or vi-style editing commands. Editing allows corrections to be made without having to erase back to the point of error or start the command line anew. The editing facilities include a feature that allows users to complete command and file names. The Bash line editing library is fully customizable. Users may define their own key bindings -- the action taken when a key is pressed. A number of variables to fine-tune editing behavior are also available. History and Command Re-entry The Bash history feature remembers commands entered to the shell and allows them to be recalled and re-executed. The history list may be of unlimited size. Bash allows users to search for previous commands and reuse portions of those commands when composing new ones. The history list may be saved across shell sessions. Bash allows users to control which commands are saved on the history list. Job Control On systems that support it, Bash provides an interface to the operating system's job control facilities, which allow processes to be suspended and restarted, and moved between the foreground and background. Bash allows users to selectively `forget' about background jobs. Shell Functions and Aliases These mechanisms are available to bind a user-selected identifier to a list of commands that will be executed when the identifier is used as a command name. Functions allow local variables and recursion, and have access to the environment of the calling shell. Aliases may be used to create a mnemonic for a command name, expand a single word to a complex command, or ensure that a command is called with a basic set of options. Arrays Bash-2.0 supports indexed arrays of unlimited size. The subscript for an array is an arithmetic expression. Arrays may be assigned to with a new compound assignment syntax, and several builtins have options to operate on array variables. Bash includes a number of built-in array variables. Arithmetic Bash allows users to perform integer arithmetic in any base from two to sixty-four. Nearly all of the C language arithmetic operators are available with the same syntax and precedence as in C. Arithmetic expansion allows an arithmetic expression to be evaluated and the result substituted into the command line. Shell variables can be used as operands, and the value of an expression may be assigned to a variable. An arithmetic expression may be used as a command; the exit status of the command is the value of the expression. ANSI-C Quoting There is a new quoting syntax that allows backslash-escaped characters in strings to be expanded according to the ANSI C standard. Tilde Expansion Users' home directories may be expanded using this feature. Words beginning with a tilde may also be expanded to the current or previous working directory. Brace Expansion Brace expansion is a convenient way to generate a list of strings that share a common prefix or suffix. Substring Capabilities Bash allows new strings to be created by removing leading or trailing substrings from existing variable values, or by specifying a starting offset and length. Portions of variable values may be matched against shell patterns and the matching portion removed or a new value substituted. Indirect Variable Expansion Bash makes it easy to find the value of a shell variable whose name is the value of another variable. Expanded I/O Capabilities Bash provides several input and output features not available in sh, including the ability to: o specify a file or file descriptor for both input and output o read from or write to asynchronous processes using named pipes o read lines ending in backslash o display a prompt on the terminal before a read o format menus and interpret responses to them o echo lines exactly as input without escape processing Control of Builtin Commands Bash implements several builtin commands to give users more control over which commands are executed. The enable builtin allows other builtin commands to be selectively enabled or disabled. The command and builtin builtins change the order in which the shell searches for commands. On systems that provide dynamic loading, new builtins may be loaded into a running shell from a shared object file. These new builtins have access to all of the shell facilities. Help Bash includes a built-in help facility. Shell Optional Behavior There is a great deal of customizable shell behavior. The shopt builtin command provides a unified interface that allows users to alter shell defaults. Prompt Customization Bash allows the primary and secondary prompts to be customized by interpreting a number of backslash-escaped special characters. Parameter and variable expansion is also performed on the values of the primary and secondary prompt strings before they are displayed. Security Bash provides a restricted shell environment. It is also possible to control the execution of setuid/setgid scripts. Directory Stack Bash provides a `directory stack', to which directories may be added and removed. The current directory may be changed to any directory in the stack. It is easy to toggle between two directories in the stack. The directory stack may be saved and restored across different shell invocations. POSIX Mode Bash is nearly completely conformant to POSIX.2. POSIX mode changes those few areas where the Bash default behavior differs from the standard to match the standard. In POSIX mode, Bash is POSIX.2 compliant. Internationalization Bash provides a new quoting syntax that allows strings to be translated according to the current locale. The locale in which the shell itself runs may also be changed, so that the shell messages themselves may be language-specific. The command-line editing facilities allow the input of eight-bit characters, so most of the ISO-8859 family of character sets are supported. Command Timing Bash allows external commands, shell builtin commands and shell functions to be timed. The format used to display the timing information may be changed by the user. --- NEW FILE: bash.1 --- .\" .\" MAN PAGE COMMENTS to .\" .\" Chet Ramey .\" Information Network Services .\" Case Western Reserve University .\" ch...@in... .\" .\" Last Change: Mon Jul 15 15:20:56 EDT 2002 .\" .\" bash_builtins, strip all but Built-Ins section .if \n(zZ=1 .ig zZ .if \n(zY=1 .ig zY .TH BASH 1 "2002 July 15" "GNU Bash-2.05b" .\" .\" There's some problem with having a `@' .\" in a tagged paragraph with the BSD man macros. .\" It has to do with `@' appearing in the }1 macro. .\" This is a problem on 4.3 BSD and Ultrix, but Sun [...8323 lines suppressed...] .PP Aliases are confusing in some uses. .PP Shell builtin commands and functions are not stoppable/restartable. .PP Compound commands and command sequences of the form `a ; b ; c' are not handled gracefully when process suspension is attempted. When a process is stopped, the shell immediately executes the next command in the sequence. It suffices to place the sequence of commands between parentheses to force it into a subshell, which may be stopped as a unit. .PP Commands inside of \fB$(\fP...\fB)\fP command substitution are not parsed until substitution is attempted. This will delay error reporting until some time after the command is entered. .PP Array variables may not (yet) be exported. .zZ .zY --- NEW FILE: README --- This directory contains the bash documentation. FAQ - a set of frequently-asked questions about Bash with answers INTRO - a short introduction to bash article.ms - an article I wrote about bash for The Linux Journal bash.1 - the bash man page builtins.1 - a man page that documents the builtins, extracted from bash.1 bashref.texi - the `bash reference manual' bashref.info - the `bash reference manual' processed by `makeinfo' readline.3 - the readline man page The `.ps' files are postscript versions of the above. The `.html' files are HTML versions of the man page and reference manual. The `.0' files are formatted manual pages. The `.txt' versions are ascii -- the output of `groff -Tascii'. The rest of this file explains how to use the `builtins.1' man page. For each command in the list of builtins create a file in man/man1 called: ${command}.1 eg. for.1 type.1 alias.1 etc. All these files are identical as follows: jaws@jaws(264)$ cat alias.1 .so man1/builtins.1 jaws@jaws(265)$ Make sure you adjust the .so line in builtins.1 to reflect where you put it. --- NEW FILE: bashref.texi --- \input texinfo.tex @c -*- texinfo -*- @c %**start of header @setfilename bashref.info @settitle Bash Reference Manual @c %**end of header @ignore Last Change: Mon Jul 15 15:21:16 EDT 2002 @end ignore @set EDITION 2.5b @set VERSION 2.05b @set UPDATED 15 July 2002 @set UPDATE-MONTH July 2002 @iftex @finalout @end iftex [...6826 lines suppressed...] @printindex bt @node Reserved Word Index @unnumbered Index of Shell Reserved Words @printindex rw @node Variable Index @unnumbered Parameter and Variable Index @printindex vr @node Function Index @unnumbered Function Index @printindex fn @node Concept Index @unnumbered Concept Index @printindex cp @contents @bye |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:35
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/examples/scripts.noah In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/examples/scripts.noah Added Files: PERMISSION README aref.bash bash.sub.bash bash_version.bash meta.bash mktmp.bash number.bash prompt.bash remap_keys.bash require.bash send_mail.bash shcat.bash source.bash string.bash stty.bash y_or_n_p.bash Log Message: Pristine source --- NEW FILE: meta.bash --- # meta.bash --- meta key frobnications # Author: Noah Friedman <fri...@pr...> # Created: 1992-06-28 # Last modified: 1993-01-26 # Public domain # Commentary: # Code: #:docstring meta: # Usage: meta [on|off] # # An argument of "on" will make bash use the 8th bit of any input from # a terminal as a "meta" bit, i.e bash will be able to use a real meta # key. # # An argument of "off" causes bash to disregard the 8th bit, which is # assumed to be used for parity instead. #:end docstring: function meta () { case "$1" in on) bind 'set input-meta On' bind 'set output-meta on' bind 'set convert-meta off' ;; off) bind 'set input-meta Off' bind 'set output-meta off' bind 'set convert-meta on' ;; *) echo "Usage: meta [on|off]" 1>&2 ; return 1 ;; esac return 0 } provide meta # meta.bash ends here --- NEW FILE: bash_version.bash --- # bash_version.bash --- get major and minor components of bash version number # Author: Noah Friedman <fri...@pr...> # Created: 1993-01-26 # Last modified: 1993-01-26 # Public domain # Converted to bash v2 syntax by Chet Ramey # Commentary: # Code: #:docstring bash_version: # Usage: bash_version {major|minor} # # Echo the major or minor number of this version of bash on stdout, or # just echo $BASH_VERSION if no argument is given. #:end docstring: ###;;;autoload function bash_version () { local major minor case "$1" in major) echo "${BASH_VERSION/.*/}" ;; minor) major="${BASH_VERSION/.*/}" minor="${BASH_VERSION#${major}.}" echo "${minor%%.*}" ;; patchlevel) minor="${BASH_VERSION#*.*.}" echo "${minor%(*}" ;; version) minor=${BASH_VERSION/#*.*./} echo ${BASH_VERSION/%.$minor/} ;; release) echo ${BASH_VERSION%(*} ;; build) minor="${BASH_VERSION#*.*.*(}" echo ${minor%)} ;; *) echo "${BASH_VERSION}" ;; esac } provide bash_version # bash_version.bash ends here --- NEW FILE: source.bash --- # source.bash # Author: Noah Friedman <fri...@pr...> # Created: 1992-05-17 # Last modified: 1993-09-29 # Public domain # Commentary: # Code: #:docstring source: # Usage: source file ... # # Source forces file arguments to be considered in the current directory # only, unless there is an absolute path starting with `/'. I think it's # bad that the builtin "source" searches PATH, because PATH normally # contains directories with binary files that aren't useful for bash to # read and most people don't put "." first in their path. # # This "source" is capable of reading more than one file at a time. Return # value is number of failed source attempts. #:end docstring: # This function is not hygienic, but there's not much we can do about # variable name conflicts here. ###;;;autoload function source () { local -i _source_failure_count=0 local _source_file for _source_file ; do # Check first part of each filename. If it's not `/', `./', or # `../' then prepend "./" to the path to force the builtin `source' # not to go searching through PATH to find the file. case "${_source_file}" in /*|./*|../* ) ;; * ) _source_file="./${_source_file}" ;; esac builtin source "${_source_file}" || _source_failure_count="_source_failure_count + 1" done return ${_source_failure_count} } #:docstring .: # See "source" #:end docstring: # So that `.' will call function definition of `source' instead of builtin ###;;;autoload function . () { source "$@" } provide source # source.bash ends here --- NEW FILE: require.bash --- # require.bash # Author: Noah Friedman <fri...@pr...> # Created: 1992-07-08 # Last modified: 1993-09-29 # Public domain # Commentary: # These functions provide an interface based on the lisp implementation for # loading libraries when they are needed and eliminating redundant loading. # The basic idea is that each "package" (or set of routines, even if it is # only one function) registers itself with a symbol that marks a "feature" # as being "provided". If later you "require" a given feature, you save # yourself the trouble of explicitly loading it again. # # At the bottom of each package, put a "provide foobar", so when another # package has a "require foobar", it gets loaded and registered as a # "feature" that won't need to get loaded again. (See warning below for # reasons why provide should be put at the end.) # # The list of provided features are kept in the `FEATURES' variable, which # is not exported. Care should be taken not to munge this in the shell. # The search path comes from a colon-separated `FPATH' variable. It has no # default value and must be set by the user. # # Require uses `fpath_search', which works by scanning all of FPATH for a # file named the same as the required symbol but with a `.bash' appended to # the name. If that is found, it is loaded. If it is not, FPATH is # searched again for a file name the same as the feature (i.e. without any # extension). Fpath_search may be useful for doing library filename # lookups in other functions (such as a `load' or `autoload' function). # # Warning: Because require ultimately uses the builtin `source' command to # read in files, it has no way of undoing the commands contained in the # file if there is an error or if no provide statement appeared (this # differs from the lisp implementation of require, which normally undoes # most of the forms that were loaded if the require fails). Therefore, to # minize the number of problems caused by requiring a faulty package (such # as syntax errors in the source file) it is better to put the provide at # the end of the file, rather than at the beginning. # Code: # Exporting this variable would cause considerable lossage, since none of # the functions are exported (or at least, they're not guaranteed to be) export -n FEATURES #:docstring : # Null function. Provided only so that one can put page breaks in source # files without any ill effects. #:end docstring: # # (\\014 == C-l) eval "function $(echo -e \\014) () { : }" #:docstring featurep: # Usage: featurep argument # # Returns 0 (true) if argument is a provided feature. Returns 1 (false) # otherwise. #:end docstring: ###;;;autoload function featurep () { local feature="$1" case " ${FEATURES} " in *" ${feature} "* ) return 0 ;; esac return 1 } #:docstring provide: # Usage: provide symbol ... # # Register a list of symbols as provided features #:end docstring: ###;;;autoload function provide () { local feature for feature in "$@" ; do if ! featurep "${feature}" ; then FEATURES="${FEATURES} ${feature}" fi done return 0 } #:docstring require: # Usage: require feature {file} # # Load FEATURE if it is not already provided. Note that require does not # call `provide' to register features. The loaded file must do that # itself. If the package does not explicitly do a `provide' after being # loaded, require will complain about the feature not being provided on # stderr. # # Optional argument FILE means to try to load FEATURE from FILE. If no # file argument is given, require searches through FPATH (see fpath_search) # for the appropriate file. # # If the variable REQUIRE_FAILURE_FATAL is set, require will cause the # current shell invocation to exit, rather than merely return. This may be # useful for a shell script that vitally depends on a package. # #:end docstring: ###;;;autoload function require () { local feature="$1" local path="$2" local file if ! featurep "${feature}" ; then file=$(fpath_search "${feature}" "${path}") && source "${file}" if ! featurep "${feature}" ; then echo "require: ${feature}: feature was not provided." 1>&2 if [ "${REQUIRE_FAILURE_FATAL+set}" = "set" ]; then exit 1 fi return 1 fi fi return 0 } #:docstring fpath_search: # Usage: fpath_search filename {path ...} # # Search $FPATH for `filename' or, if `path' (a list) is specified, search # those directories instead of $FPATH. First the path is searched for an # occurrence of `filename.bash, then a second search is made for just # `filename'. #:end docstring: ###;;;autoload function fpath_search () { local name="$1" local path="$2" local suffix=".bash" local file if [ -z "${path}" ]; then path="${FPATH}"; fi for file in "${name}${suffix}" "${name}" ; do set -- $(IFS=':' set -- ${path} for p in "$@" ; do echo -n "${p:-.} " done) while [ $# -ne 0 ]; do test -f "${1}/${file}" && { file="${1}/${file}"; break 2 } shift done done if [ $# -eq 0 ]; then echo "fpath_search: ${name}: file not found in fpath" 1>&2 return 1 fi echo "${file}" return 0 } provide require # require.bash ends here --- NEW FILE: y_or_n_p.bash --- # y_or_n_p.bash # Author: Noah Friedman <fri...@pr...> # Created: 1992-06-18 # Last modified: 1993-03-01 # Public domain # Conversion to bash v2 syntax done by Chet Ramey # Commentary: # Code: #:docstring y_or_n_p: # Usage: y_or_n_p QUERY # # Print QUERY on stderr, then read stdin for a y-or-n response. Actually, # user may type anything they like, but first character must be a `y', `n', # `q', or `!', otherwise the question is repeated until such an answer is # obtained. # # If user typed `y', y_or_n_p returns 0. # # If user typed `n', y_or_n_p returns 1. # # If user typed `!', y_or_n_p returns 2. This is an indication to the # caller that no more queries should be made. Assume `y' for all the rest. # # If user typed `q', y_or_n_p returns 3. This is an indication to the # caller that no more queries should be made. Assume `n' for all the rest. # #:end docstring: ###;;;autoload function y_or_n_p () { local ans [ ! -t 0 ] && return 1 while read -p "$*" -e ans ; do case "${ans}" in y* | Y* ) return 0 ;; n* | N* ) return 1 ;; \! ) return 2 ;; q* | Q* ) return 3 ;; *) echo "Please answer one of \`y', \`n', \`q', or \`"\!"'" 1>&2 ;; esac done } #:docstring yes_or_no_p: # Usage: yes_or_no_p QUERY # # Like y_or_n_p, but require a full `yes', `no', `yes!', or `quit' response. #:end docstring: ###;;;autoload function yes_or_no_p () { local ans [ ! -t 0 ] && return 3 while read -p "$*" -e ans; do ans="$(echo ${ans} | tr '[A-Z]' '[a-z]')" case "${ans}" in yes ) return 0 ;; no ) return 1 ;; yes\! ) return 2 ;; quit ) return 3 ;; *) echo "Please answer \`yes', \`no', \`yes"\!"', or \`quit'" 1>&2 ;; esac done } provide y_or_n_p # y_or_n_p.bash ends here --- NEW FILE: number.bash --- # number.bash # Author: Noah Friedman <fri...@pr...> # Created: 1993-02-22 # Last modified: 1993-04-01 # Public domain # Conversion to bash v2 syntax done by Chet Ramey # Commentary: # Code: #:docstring number: # Usage: number [number] # # Converts decimal integers to english notation. Spaces and commas are # optional. Numbers 67 digits and larger will overflow this script. # # E.g: number 99,000,000,000,000,454 # => ninety-nine quadrillion four hundred fifty-four # #:end docstring: function number () { local result local val1 local val2 local val3 local d1 local d2 local d3 case "$*" in *[!0-9,.]* ) echo "number: invalid character in argument." 1>&2 return 1 ;; *.* ) echo "number: fractions not supported (yet)." 1>&2 return 1 ;; esac result='' eval set - "`echo ${1+\"$@\"} | sed -n -e ' s/[, ]//g;s/^00*/0/g;s/\(.\)\(.\)\(.\)$/\"\1 \2 \3\"/; :l /[0-9][0-9][0-9]/{ s/\([^\" ][^\" ]*\)\([^\" ]\)\([^\" ]\)\([^\" ]\)/\1\"\2 \3 \4\"/g; t l } /^[0-9][0-9][0-9]/s/\([^\" ]\)\([^\" ]\)\([^\" ]\)/\"\1 \2 \3\"/; /^[0-9][0-9]/s/\([^\" ]\)\([^\" ]\)/\"\1 \2\"/; /^[0-9]/s/^\([^\" ][^\" ]*\)/\"\1\"/g;s/\"\"/\" \"/g;p;'`" while test $# -ne 0 ; do eval `set - $1; d3='' d2='' d1='' case $# in 1 ) d1=$1 ;; 2 ) d2=$1 d1=$2 ;; 3 ) d3=$1 d2=$2 d1=$3 ;; esac echo "d3=\"${d3}\" d2=\"${d2}\" d1=\"${d1}\""` val1='' val2='' val3='' case "${d3}" in '1' ) val3='one' ;; '2' ) val3='two' ;; '3' ) val3='three' ;; '4' ) val3='four' ;; '5' ) val3='five' ;; '6' ) val3='six' ;; '7' ) val3='seven' ;; '8' ) val3='eight' ;; '9' ) val3='nine' ;; esac case "${d2}" in '1' ) val2='teen' ;; '2' ) val2='twenty' ;; '3' ) val2='thirty' ;; '4' ) val2='forty' ;; '5' ) val2='fifty' ;; '6' ) val2='sixty' ;; '7' ) val2='seventy' ;; '8' ) val2='eighty' ;; '9' ) val2='ninety' ;; esac case "${val2}" in 'teen') val2='' case "${d1}" in '0') val1='ten' ;; '1') val1='eleven' ;; '2') val1='twelve' ;; '3') val1='thirteen' ;; '4') val1='fourteen' ;; '5') val1='fifteen' ;; '6') val1='sixteen' ;; '7') val1='seventeen' ;; '8') val1='eighteen' ;; '9') val1='nineteen' ;; esac ;; 0 ) : ;; * ) if test ".${val2}" != '.' -a ".${d1}" != '.0' ; then val2="${val2}-" fi case "${d1}" in '0') val2="${val2} " ;; '1') val1='one' ;; '2') val1='two' ;; '3') val1='three' ;; '4') val1='four' ;; '5') val1='five' ;; '6') val1='six' ;; '7') val1='seven' ;; '8') val1='eight' ;; '9') val1='nine' ;; esac ;; esac if test ".${val3}" != '.' ; then result="${result}${val3} hundred " fi if test ".${val2}" != '.' ; then result="${result}${val2}" fi if test ".${val1}" != '.' ; then result="${result}${val1} " fi if test ".${d1}${d2}${d3}" != '.000' ; then case $# in 0 | 1 ) ;; 2 ) result="${result}thousand " ;; 3 ) result="${result}million " ;; 4 ) result="${result}billion " ;; 5 ) result="${result}trillion " ;; 6 ) result="${result}quadrillion " ;; 7 ) result="${result}quintillion " ;; 8 ) result="${result}sextillion " ;; 9 ) result="${result}septillion " ;; 10 ) result="${result}octillion " ;; 11 ) result="${result}nonillion " ;; 12 ) result="${result}decillion " ;; 13 ) result="${result}undecillion " ;; 14 ) result="${result}duodecillion " ;; 15 ) result="${result}tredecillion " ;; 16 ) result="${result}quattuordecillion " ;; 17 ) result="${result}quindecillion " ;; 18 ) result="${result}sexdecillion " ;; 19 ) result="${result}septendecillion " ;; 20 ) result="${result}octodecillion " ;; 21 ) result="${result}novemdecillion " ;; 22 ) result="${result}vigintillion " ;; * ) echo "Error: number too large (66 digits max)." 1>&2 return 1 ;; esac fi shift done set - ${result} case "$*" in '') set - 'zero' ;; esac echo ${1+"$@"} } provide number # number.bash ends here --- NEW FILE: PERMISSION --- >From fri...@cl... Thu May 25 12:19:06 1995 Flags: 10 Return-Path: fri...@cl... Received: from po.cwru.edu (ro...@po... [129.22.4.2]) by odin.INS.CWRU.Edu with ESMTP (8.6.10+cwru/CWRU-2.1-ins) id MAA08685; Thu, 25 May 1995 12:19:05 -0400 (from fri...@cl... for <ch...@od...>) Received: from cli.com (cli.com [192.31.85.1]) by po.cwru.edu with SMTP (8.6.10+cwru/CWRU-2.3) id MAA11299; Thu, 25 May 1995 12:19:00 -0400 (from fri...@cl... for <ch...@po...>) Received: from tepui.cli.com by cli.com (4.1/SMI-4.1) id AA27213; Thu, 25 May 95 11:18:25 CDT Received: by tepui.cli.com (4.1) id AA16031; Thu, 25 May 95 11:18:23 CDT Message-Id: <950...@te...> From: fri...@gn... (Noah Friedman) To: ch...@po... Subject: Bash scripts Reply-To: fri...@gn... In-Reply-To: <ch...@od...> Thu, 25 May 1995 11:19:59 -0400 References: <950...@od...> Date: Thu, 25 May 95 11:18:21 CST >Hi. I snagged some of your bash functions from your home directory on >the FSF machines (naughty, I know), and I was wondering if you'd let >me distribute them with bash-2.0. Thanks. Sure. I think there's a later copy in ~ftp/friedman/shell-inits/init-4.89.tar.gz. There are also some elisp and es frobs in that file. It should serve as a pretty good example of how to get carried away. :-) --- NEW FILE: stty.bash --- # stty.bash # Author: Noah Friedman <fri...@pr...> # Created: 1992-01-11 # Last modified: 1993-09-29 # Public domain # Conversion to bash v2 syntax done by Chet Ramey # Commentary: # Code: require remap_keybindings #:docstring stty: # Track changes to certain keybindings with stty, and make those changes # reflect in bash's readline bindings as well. # # This requires bash version 1.10 or newer, since previous versions did not # implement the `bind' builtin. #:end docstring: ###;;;autoload function stty () { local erase="backward-delete-char" local kill="unix-line-discard" local werase="backward-kill-word" local lnext="quoted-insert" local readline_function="" local key="" local stty_command="" while [ $# -gt 0 ]; do case "$1" in erase | kill | werase | lnext ) key=$(echo "${2}" | cat -v | sed 's/\^/\\C-/') readline_function=$(eval echo \$${1}) # Get rid of any current bindings; the whole point of this # function is to make the distinction between readline # bindings and particular cbreak characters transparent; old # readline keybindings shouldn't hang around. # could use bind -r here instead of binding to self-insert remap_keybindings "${readline_function}" "self-insert" # Bind new key to appropriate readline function bind "\"${key}\": ${readline_function}" stty_command="${stty_command} ${1} ${2}" shift 2 ;; *) stty_command="${stty_command} ${1}" shift ;; esac done command stty ${stty_command} } provide stty # stty.bash ends here --- NEW FILE: send_mail.bash --- # send_mail.bash # Author: Noah Friedman <fri...@pr...> # Created: 1992-07-02 # Public domain # Commentary: # TODO: implement Fcc headers (see emacs manual) # Code: #:docstring send_mail: # Usage: send_mail # # This function serves as a simple replacement for sendmail as a client # interface on those systems where it is not available. It does assume # that one can talk to an SMTP mailer on port 25 either on the local host # or on the host specified by the MAILHOST environment variable. If you # have access to sendmail, it's better to use 'sendmail -t' instead of this # script (which probably isn't as robust). # # Message is read from stdin, and headers are parsed to determine # recipients. #:end docstring: ###;;;autoload function send_mail () { # Need gawk, since several extensions are taken advantage of (like # IGNORECASE for regexps). local awk="${GAWK_LOCATION:-gawk}" local DefaultFrom="${USER:-${LOGNAME}}" local From local To local Cc local Bcc local tmpfile="/tmp/send_mail$$" while [ -e "${tmpfile}" ]; do tmpfile="/tmp/send_mail${RANDOM}" done # Lines consisting only of dots need one more dot appended. SMTP # servers eat one of the dots (and if only 1 dot appears, it signifies # the end of the message). sed '/^\.\.*/s/^\(\.\.*\)$/\1./' > "${tmpfile}" # Parse mail headers in message to extract recipients list. # This doesn't affect what the user sees---it's only used to generate # the rcpt-to lines for SMTP. eval $(${awk} -f - "${tmpfile}" <<- '__EOF__' # Try to extract email address from amidst random data function parse_address (data) { # From: "real name" <foobar@host> # From: "" <foobar@host> if (match(data, /^\"[^\"]*\"[ \t]*<.*>/)) { data_idx = match(data, /^\"[^\"]*\"[ \t]*</) data = substr(data, RSTART + RLENGTH); if (data_idx = match(data, ">.*")) data = substr(data, 1, RSTART - 1); return data } # From: real name <foobar@host> if (match(data, /<.*>/)) { data_idx = match(data, /</) data = substr(data, RSTART + RLENGTH); if (data_idx = match(data, ">")) data = substr(data, 1, RSTART - 1); return data } # From: foobar@host (real name) if (match(data, /\(.*\)/)) { data_idx = match(data, /\(/); data = substr(data, 1, RSTART - 1); return data } # (hopefully) From: foobar@host return data } BEGIN { IGNORECASE = 1; } # Blank line signifies end of headers, so we can stop looking. /^$/ { exit(0) } /^from:|^to:|^cc:|^bcc:/ { header_idx = match($0, /^[^:]*:/) if (header_idx) { # Capitalize header name header_firstchar = toupper(substr($0, RSTART, 1)); header_rest = tolower(substr($0, RSTART + 1, RLENGTH - 2)); header = header_firstchar header_rest $0 = substr($0, RSTART + RLENGTH + 1); addresses = "" # parse addresses while ($0) { # Strip leading whitespace if (idx = match($0, /[ \t]*/)) $0 = substr($0, RSTART + RLENGTH); # Find everything up to a nonquoted comma # FIXME: doesnt handle quoting yet if (idx = match($0, /,/)) { data = substr($0, 1, RSTART); $0 = substr($0, RSTART + 1); } else { data = $0 $0 = "" } addresses = addresses " " parse_address(data) } printf("%s='%s'\n", header, addresses); } } __EOF__) # Not sure if an address is *required* after the HELO.. every sendmail # I tried talking to didn't seem to care. Some sendmails don't care # if there's a HELO at all. cat <<- __EOF__ | telnet ${MAILHOST:-localhost} 25 > /dev/null 2>&1 HELO mail from: ${From:-${DefaultFrom}} $(for name in ${To} ${Cc} ${Bcc} ; do echo "rcpt to: ${name}" done) data $(cat "${tmpfile}") . quit __EOF__ rm -f "${tmpfile}" } provide send_mail # send_mail.bash ends here --- NEW FILE: bash.sub.bash --- # bash.sub.bash --- stub for standalone shell scripts using bash library # Author: Noah Friedman <fri...@pr...> # Created: 1992-07-13 # Last modified: 1993-09-29 # Public domain #:docstring bash.sub: # Standard subroutines for bash scripts wishing to use "require" to load # libraries. # # Usage: In each directory where a bash script that uses this script # exists, place a copy of this script. Then, at the top of such scripts, # put the command # # source ${0%/*}/bash.sub || exit 1 # # Then you can use `require' to load packages. # #:end docstring: default_FPATH="~friedman/etc/init/bash/functions/lib" source "${default_FPATH}/feature" REQUIRE_FAILURE_FATAL=t FPATH="${FPATH-${default_FPATH}}" # bash.sub.bash ends here --- NEW FILE: shcat.bash --- # shcat.bash # Author: Noah Friedman <fri...@pr...> # Created: 1992-07-17 # Last modified: 1993-09-29 # Public domain # Conversion to bash v2 syntax done by Chet Ramey # Commentary: # Code: #:docstring shcat: # Usage: shcat {file1} {file2} {...} # # Like `cat', only this is all inline bash. #:end docstring: ###;;;autoload function shcat () { local IFS="" local line local file local exitstat=0 if [ $# -eq 0 ]; then while read -r line; do echo "${line}" done return 0 else for file in "$@" ; do if [ -r "${file}" ]; then while read -r line; do echo "${line}" done < "${file}" else # This will cause the error to be printed on stderr < "${file}" exitstat=1 fi done return ${exitstat} fi } provide shcat # shcat.bash ends here --- NEW FILE: mktmp.bash --- # mktmp.bash # Author: Noah Friedman <fri...@pr...> # Created: 1993-02-03 # Last modified: 1993-02-03 # Public domain # Conversion to bash v2 syntax done by Chet Ramey # Commentary: # Code: #:docstring mktmp: # Usage: mktmp [template] {createp} # # Generate a unique filename from TEMPLATE by appending a random number to # the end. # # If optional 2nd arg CREATEP is non-null, file will be created atomically # before returning. This is to avoid the race condition that in between # the time that the temporary name is returned and the caller uses it, # someone else creates the file. #:end docstring: ###;;;autoload function mktmp () { local template="$1" local tmpfile="${template}${RANDOM}" local createp="$2" local noclobber_status case "$-" in *C*) noclobber_status=set;; esac if [ "${createp:+set}" = "set" ]; then # Version which creates file atomically through noclobber test. set -o noclobber (> "${tmpfile}") 2> /dev/null while [ $? -ne 0 ] ; do # Detect whether file really exists or creation lost because of # some other permissions problem. If the latter, we don't want # to loop forever. if [ ! -e "${tmpfile}" ]; then # Trying to create file again creates stderr message. echo -n "mktmp: " 1>&2 > "${tmpfile}" return 1 fi tmpfile="${template}${RANDOM}" (> "${tmpfile}") 2> /dev/null done test "${noclobber_status}" != "set" && set +o noclobber else # Doesn't create file, so it introduces race condition for caller. while [ -e "${tmpfile}" ]; do tmpfile="${template}${RANDOM}" done fi echo "${tmpfile}" } provide mktmp # mktmp.bash ends here --- NEW FILE: prompt.bash --- # prompt.bash # Author: Noah Friedman <fri...@pr...> # Created: 1992-01-15 # Public domain # $Id: prompt.bash,v 1.1 2005/05/22 10:13:19 earnie Exp $ # Commentary: # Code: #:docstring prompt: # Usage: prompt [chars] # # Various preformatted prompt strings selected by argument. For a # list of available arguments and corresponding formats, do # `type prompt'. #:end docstring: ###;;;autoload function prompt () { case "$1" in d) PS1='$(dirs) \$ ' ;; n) PS1='\$ ' ;; hsw) PS1='\h[$SHLVL]: \w \$ ' ;; hw) PS1='\h: \w \$ ' ;; sh) PS1='[$SHLVL] \h\$ ' ;; sw) PS1='[$SHLVL] \w \$ ' ;; uh) PS1='\u@\h\$ ' ;; uhsHw) PS1='\u@\h[$SHLVL]:\#: \w \$ ' ;; uhsw) PS1='\u@\h[$SHLVL]: \w \$ ' ;; uhw) PS1='\u@\h: \w \$ ' ;; uw) PS1='(\u) \w \$ ' ;; w) PS1='\w \$ ' ;; esac } provide prompt # prompt.bash ends here --- NEW FILE: README --- This collection of scripts was originally written for older versions of bash by Noah Friedman (fri...@gn...). The conversion to bash v2 syntax was done by Chet Ramey. These scripts are as-is; there is no copyright associated with any of them. They exist simply as examples of bash scripting. Here's a description of what's in this directory: aref.bash pseudo-arrays and substring indexing examples bash.sub.bash library functions used by require.bash bash_version.bash a function to slice up $BASH_VERSION meta.bash enable and disable eight-bit readline input mktmp.bash make a temporary file with a unique name number.bash a fun hack to translate numerals into english prompt.bash a way to set PS1 to some predefined strings remap_keys.bash a front end to `bind' to redo readline bindings require.bash lisp-like require/provide library functions for bash send_mail.bash replacement smtp client written in bash shcat.bash bash replacement for `cat' source.bash replacement for source that uses current directory string.bash the string(3) functions at the shell level stty.bash front-end to stty that changes readline bindings too y_or_n_p.bash prompt for a yes/no/quit answer --- NEW FILE: remap_keys.bash --- # remap_keybindings.bash # Author: Noah Friedman <fri...@pr...> # Created: 1992-01-11 # Last modified: 1993-02-03 # Public domain # Conversion to bash v2 syntax done by Chet Ramey # Commentary: # Code: #:docstring remap_keybindings: # Usage: remap_keybindings old_function new_function # # Clear all readline keybindings associated with OLD_FUNCTION (a Readline # function) rebinding them to NEW_FUNCTION (`self-insert' by default) # # This requires bash version 1.10 or newer, since previous versions did not # implement the `bind' builtin. #:end docstring: ###;;;autoload function remap_keybindings () { local unbind_function="$1" local bind_function="${2:-'self-insert'}" local bind_output local arg # If they're the same thing, the work has already been done. :-) if [ "${unbind_function}" = "${bind_function}" ]; then return 0 fi while : ; do bind_output="$(bind -q ${unbind_function} 2> /dev/null)" case "${bind_output}" in "${unbind_function} can be invoked via"* ) ;; "" ) return 1 ;; # probably bad argument to bind *) return 0 ;; # unbound esac # Format of bind_output is like: # 'quoted-insert can be invoked via "\C-q", "\C-v".' # 'self-insert can be invoked via " ", "!", """, "$", "%", ...' set -- ${bind_output} shift 5 for arg in "$@" ; do # strip off trailing `.' or `,' arg=${arg%.}; arg=${arg%,}; case ${arg} in ..) # bind -q didn't provide whole list of key bindings; jump # to top loop to get more continue 2 ; ;; *) bind "${arg}: ${bind_function}" ;; esac done done } provide remap_keybindings # remap_keybindings.bash ends here --- NEW FILE: aref.bash --- # aref.bash --- pseudo-array manipulating routines # Author: Noah Friedman <fri...@pr...> # Created 1992-07-01 # Last modified: 1993-02-03 # Public domain # Conversion to bash v2 syntax done by Chet Ramey # Commentary: # Code: #:docstring aref: # Usage: aref NAME INDEX # # In array NAME, access element INDEX (0-origin) #:end docstring: ###;;;autoload function aref () { local name="$1" local index="$2" set -- ${!name} [ $index -ge 1 ] && shift $index echo $1 } #:docstring string_aref: # Usage: aref STRING INDEX # # Echo the INDEXth character in STRING (0-origin) on stdout. #:end docstring: ###;;;autoload function string_aref () { local stuff=${1:$2} echo ${stuff:0:1} } provide aref # aref.bash ends here --- NEW FILE: string.bash --- # string.bash --- bash emulation of string(3) library routines # Author: Noah Friedman <fri...@pr...> # Created: 1992-07-01 # Last modified: 1993-09-29 # Public domain # Conversion to bash v2 syntax done by Chet Ramey # Commentary: # Code: #:docstring strcat: # Usage: strcat s1 s2 # # Strcat appends the value of variable s2 to variable s1. # # Example: # a="foo" # b="bar" # strcat a b # echo $a # => foobar # #:end docstring: ###;;;autoload function strcat () { local s1_val s2_val s1_val=${!1} # indirect variable expansion s2_val=${!2} eval "$1"=\'"${s1_val}${s2_val}"\' } #:docstring strncat: # Usage: strncat s1 s2 $n # # Line strcat, but strncat appends a maximum of n characters from the value # of variable s2. It copies fewer if the value of variabl s2 is shorter # than n characters. Echoes result on stdout. # # Example: # a=foo # b=barbaz # strncat a b 3 # echo $a # => foobar # #:end docstring: ###;;;autoload function strncat () { local s1="$1" local s2="$2" local -i n="$3" local s1_val s2_val s1_val=${!s1} # indirect variable expansion s2_val=${!s2} if [ ${#s2_val} -gt ${n} ]; then s2_val=${s2_val:0:$n} # substring extraction fi eval "$s1"=\'"${s1_val}${s2_val}"\' } #:docstring strcmp: # Usage: strcmp $s1 $s2 # # Strcmp compares its arguments and returns an integer less than, equal to, # or greater than zero, depending on whether string s1 is lexicographically # less than, equal to, or greater than string s2. #:end docstring: ###;;;autoload function strcmp () { [ "$1" = "$2" ] && return 0 [ "${1}" '<' "${2}" ] > /dev/null && return -1 return 1 } #:docstring strncmp: # Usage: strncmp $s1 $s2 $n # # Like strcmp, but makes the comparison by examining a maximum of n # characters (n less than or equal to zero yields equality). #:end docstring: ###;;;autoload function strncmp () { if [ -z "${3}" -o "${3}" -le "0" ]; then return 0 fi if [ ${3} -ge ${#1} -a ${3} -ge ${#2} ]; then strcmp "$1" "$2" return $? else s1=${1:0:$3} s2=${2:0:$3} strcmp $s1 $s2 return $? fi } #:docstring strlen: # Usage: strlen s # # Strlen returns the number of characters in string literal s. #:end docstring: ###;;;autoload function strlen () { eval echo "\${#${1}}" } #:docstring strspn: # Usage: strspn $s1 $s2 # # Strspn returns the length of the maximum initial segment of string s1, # which consists entirely of characters from string s2. #:end docstring: ###;;;autoload function strspn () { # Unsetting IFS allows whitespace to be handled as normal chars. local IFS= local result="${1%%[!${2}]*}" echo ${#result} } #:docstring strcspn: # Usage: strcspn $s1 $s2 # # Strcspn returns the length of the maximum initial segment of string s1, # which consists entirely of characters not from string s2. #:end docstring: ###;;;autoload function strcspn () { # Unsetting IFS allows whitspace to be handled as normal chars. local IFS= local result="${1%%[${2}]*}" echo ${#result} } #:docstring strstr: # Usage: strstr s1 s2 # # Strstr echoes a substring starting at the first occurrence of string s2 in # string s1, or nothing if s2 does not occur in the string. If s2 points to # a string of zero length, strstr echoes s1. #:end docstring: ###;;;autoload function strstr () { # if s2 points to a string of zero length, strstr echoes s1 [ ${#2} -eq 0 ] && { echo "$1" ; return 0; } # strstr echoes nothing if s2 does not occur in s1 case "$1" in *$2*) ;; *) return 1;; esac # use the pattern matching code to strip off the match and everything # following it first=${1/$2*/} # then strip off the first unmatched portion of the string echo "${1##$first}" } #:docstring strtok: # Usage: strtok s1 s2 # # Strtok considers the string s1 to consist of a sequence of zero or more # text tokens separated by spans of one or more characters from the # separator string s2. The first call (with a non-empty string s1 # specified) echoes a string consisting of the first token on stdout. The # function keeps track of its position in the string s1 between separate # calls, so that subsequent calls made with the first argument an empty # string will work through the string immediately following that token. In # this way subsequent calls will work through the string s1 until no tokens # remain. The separator string s2 may be different from call to call. # When no token remains in s1, an empty value is echoed on stdout. #:end docstring: ###;;;autoload function strtok () { : } #:docstring strtrunc: # Usage: strtrunc $n $s1 {$s2} {$...} # # Used by many functions like strncmp to truncate arguments for comparison. # Echoes the first n characters of each string s1 s2 ... on stdout. #:end docstring: ###;;;autoload function strtrunc () { n=$1 ; shift for z; do echo "${z:0:$n}" done } provide string # string.bash ends here |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:35
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/examples/scripts.v2 In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/examples/scripts.v2 Added Files: PERMISSION README arc2tarz bashrand cal2day.bash cdhist.bash corename fman frcp lowercase ncp newext nmv pages pf pmtop ren rename repeat shprof untar uudec uuenc vtree where Log Message: Pristine source --- NEW FILE: rename --- #! /bin/bash # # original from: # @(#) rename.ksh 1.1 94/05/10 # 90/06/01 John DuBois (sp...@ar...) # 91/02/25 Improved help info # 92/06/07 remove quotes from around shell pattern as required by new ksh # 94/05/10 Exit if no globbing chars given. # # conversion to bash v2 syntax by Chet Ramey phelp() { echo "$usage All files that match oldpattern will be renamed with the filename components that match the constant parts of oldpattern changed to the corresponding constant parts of newpattern. The components of the filename that match variable parts of oldpattern will be preserved. Variable parts in oldpattern must occur in the same order in newpattern. Variables parts can be '?' and '*'. Example: rename \"/tmp/foo*.ba.?\" \"/tmp/new*x?\" All files in /tmp that match foo*.ba.? will have the \"foo\" part replaced by \"new\" and the \".ba.\" part replaced by \"x\"." } usage="usage: $name [-htv] oldpattern newpattern" name=${0##/} while getopts "htv" opt; do case "$opt" in t) tell=true;; v) verbose=true;; h) phelp; exit 0;; *) echo "$name: $usage" 1>&2; exit 2;; esac done shift $((OPTIND - 1)) if [ $# -lt 2 ]; then phelp exit 2 fi oldpat=$1 newpat=$2 set -- $1 if [ ! -e "$1" ]; then echo "$name: no files match $oldpat." exit 1 fi typeset -i i=1 j # Example oldpat: foo*.a # Example newpat: bar*.b # Examples given for first iteration (in the example, the only interation) while :; do case "$oldpat" in *[\*\?]*) ;; *) break;; esac # Get leftmost globbing pattern in oldpat pat=${oldpat#*[\*\?]} # pat=.a pat=${oldpat%%"$pat"} # pat=foo* pat=${pat##*[!\?\*]} # pat=* # Find parts before & after pattern oldpre[i]=${oldpat%%"$pat"*} # oldpre[1]=foo oldsuf[i]=${oldpat#*"$pat"} # oldsuf[1]=.a newpre[i]=${newpat%%"$pat"*} # newpre[1]=bar # Get rid of processed part of patterns oldpat=${oldpat#${oldpre[i]}"$pat"} # oldpat=.a newpat=${newpat#${newpre[i]}"$pat"} # newpat=.b let i=i+1 done if [ $i -eq 1 ]; then echo "No globbing chars in pattern." 1>&2 exit 1 fi oldpre[i]=${oldpat%%"$pat"*} # oldpre[2]=.a oldsuf[i]=${oldpat#*"$pat"} # oldsuf[2]=.a newpre[i]=${newpat%%"$pat"*} # newpre[2]=.b if [ -n "$verbose" ]; then j=1 while let "j < i"; do echo \ "Old prefix: ${oldpre[j]} Old suffix: ${oldsuf[j]} New prefix: ${newpre[j]}" let j=j+1 done fi # Example file: foox.a for file; do j=1 origname=$file # origname=foox.a newfile= while let "j <= i"; do # Peel off a prefix interation 1 2 file=${file#${oldpre[j]}} # file=x.a file= # Save the part of this prefix that is to be retained const=${file%${oldsuf[j]}} # const=x const= newfile=$newfile${newpre[j]}$const # newfile=barx newfile=barx.b file=${file#$const} # file=.a file=.a let j=j+1 done if [ -n "$tell" ]; then echo "Would move \"$origname\" to \"$newfile\"." else if [ -n "$verbose" ]; then echo "Moving \"$origname\" to \"$newfile\"." fi mv $origname $newfile fi done --- NEW FILE: nmv --- #! /bin/bash # # original from: # @(#) ncp.ksh,nmv.ksh 1.1 94/07/23 # 92/01/18 john h. dubois iii (jo...@ar...) # 92/01/31 added check for no args left after shifts # 92/02/17 added help # 92/02/25 remove path component from filename before tacking it onto dest. # 92/03/15 exec mv or cp # 93/07/13 Added -i # 93/09/29 Made abort if file exists optional. # 93/11/19 Exit before invoking mv if no files to move # 94/01/03 Added o option # 94/04/13 Added x option. # Fixed appending of source filename, broken by earlier change. # 94/07/23 Append only the filename part of the source path. # # conversion to bash v2 syntax done by Chet Ramey false() { return 1 } true() { return 0 } phelp() { echo "$name: do a $cmd with extra checking and options. $Usage $name is used as a front end for $cmd to get the [icfo] options, and so that a trailing / will force the last component of the path to be interpreted as a directory, so that $name foo bar/ will fail if bar is not an existing directory, instead of changing the name of foo to bar. Effectively, $name foo bar/ is short for $name foo bar/foo Options: -h prints this help. -c checks first for the existence of each file, and fails if it exists. -i is like -c except that if the file exists and stdin and stdout are a tty, a query is printed and a reply is read; a file is overwritten only if the reply begins with 'y'. -f unsets -c and -i (in case $cmd is aliased to $name). -o (overwrite only) checks that the named file(s) exist and fails for any that do not. It is the complement of the -c option. Whichever of [cifo] comes later on the command line determines the behaviour. Any of these options must come before any standard $cmd options." } # interactive: Attempt to overwrite file should result in interactive # query rather than automatic failure. # noover: Do not overwrite files (if interactive is true, query, else fail) # overwrite: Only overwriting is allowed, not creation of new files. # debug: Print debugging info. typeset interactive=false noover=false overwrite=false debug=false name=${0##*/} case "$name" in ncp|nmv) cmd=/bin/${name#?} ;; *) echo "$name: Must be invoked as ncp or nmv." 1>&2 ; exit 2;; esac Usage="Usage: $name [-cfhio] $cmd-cmd-line" while getopts :cfhiox opt; do case $opt in h) phelp; exit 0;; x) debug=true ;; c) noover=true ;; i) noover=true ; interactive=true ;; f) noover=false ; interactive=false ;; o) overwrite=true ; noover=false ; interactive=false;; +?) echo "$name: options should not be preceded by a '+'." 1>&2; exit 2;; ?) echo "$name: $OPTARG: bad option. Use -h for help." 1>&2 ; exit 2;; esac done # remove args that were options shift $((OPTIND - 1)) if [ $# -lt 2 ]; then echo -e "$Usage\nUse -h for help." exit fi Check() { if [ ! -f "$1" ] && $overwrite; then echo "$name: $1: File does not exist." 1>&2 return 1 elif [ -f "$1" ] && $noover; then if [ $interactive = false ] || [ ! -t 0 ] || [ ! -t 1 ]; then echo "$name: $1: File exists." 1>&2 return 1 else while :; do echo -n \ "$name: $1: File exists. Overwrite? (y)es/(n)o/(a)bort/(Y)es for all: " 1>&2 read reply case "$reply" in y*) echo "$name: Overwriting $1." return 0 ;; Y*) echo "$name: Overwriting $1." interactive=false noover=false return 0 ;; [nN]*) echo "$name: Skipping $2." return 1 ;; [aA]*) echo "$name: Aborting." exit 1 ;; *) echo "$name: Invalid response." 1>&2 ;; esac done fi else return 0 fi } # i is the index of the filename being examined # lastarg is the index of the last filename before the dest directory name typeset -i i=0 lastarg=$(($#-1)) # Sets argv[0..$#-1] argv=("$@") $debug && echo argv = "${argv[@]}" 1>&2 dest=${argv[lastarg]} if $debug; then echo \ "interactive=$interactive noover=$noover overwrite=$overwrite debug=$debug lastarg=$lastarg dest=$dest name=$name cmd=$cmd files=$*" 1>&2 fi if $noover || $overwrite; then $debug && echo "checking for existance of directories..." 1>&2 # If the destination is not intended to be a directory... if [ $# -eq 2 ] && [ ! -d "$dest" ]; then Check "$dest" "$1" || exit 0 # No files to copy else while [ $i -lt $lastarg ]; do Check "$dest/${argv[i]##*/}" "${argv[i]}" || unset argv[i] let i+=1 done fi fi [ ${#argv[@]} -lt 2 ] && exit 0 # If only 2 args are given, mv/cp will not insist that the destination # be a directory, which we want if the destination ends in "/" or if # the original number of args was >2. # $# is still the original number of args. # Tack the file name onto the destination to force this behaviour. lastisslash() { case "$1" in */) return 0;; *) return 1;; esac } if [ ${#argv[@]} = 2 ] && { lastisslash "$2" || [ $# -gt 2 ]; }; then $debug && echo "Appending filename." 1>&2 # Don't know which element of argv[] holds the source filename, # since may have started with more than 1 source file & had some unset. # So, compact args to make it easy to find the set one. argv=("${argv[@]}") argv[1]="${argv[1]}/${argv[0]##*/}" fi $debug && echo "Executing command: $cmd ${argv[@]}" 1>&2 exec $cmd "${argv[@]}" --- NEW FILE: repeat --- #! /bin/bash # # original from: # repeat: repeat a command. # @(#) repeat.ksh 1.1 93/06/03 # 90/05 john h. dubois iii (jo...@ar...) # 90/11 added help # 93/06/03 Added s, h, p, and v options # # conversion to bash v2 syntax done by Chet Ramey istrue() { test 0 -ne "$1" } isfalse() { test 0 -eq "$1" } phelp() { echo "$name: repeatedly execute a command line. $Usage commandline is executed once for each integer from startcount through endcount inclusive. The default for startcount is 1 if a positive endcount or no endcount is given, and -1 if a negative endcount is given. A count parameter consisting of a single number is taken to be an endcount. If only an endcount is given and it is positive, commandline is executed endcount times. endcount may be less than startcount. If no endcount is given (e.g. a count parameter of \"10-\"), commandline execution repeats indefinitely with the iteration variable incrementing in a positive direction. A count parameter of consisting of \"-\" will repeat indefinitely starting with 1. Note that quoting and variables in commandline are interpreted twice, once when it is passed to the repeat command, and once when it is actually executed. The iteration variable is \"count\". If \$count is used in commandline, make sure it is quoted with ' or \. Options: -h: Print this help. -p: Print value of iteration variable on stderr before each iteration. -s <sec>: sleep for <sec> seconds after each iteration except the last. -v: Print start and end values before beginning." } name=${0##*/} Usage="Usage: repeat [-hpv] [-s <sec>] [[startcount]-][endcount] command [arg ...]" typeset -i count=1 forever=0 sleep=0 print=0 verbose=0 while getopts :0123456789hpvs: opt; do case $opt in h) phelp; exit 0;; s) sleep=$OPTARG || exit 1;; p) print=1;; v)verbose=1;; [0-9]) break;; +?) echo "$name: options should not be preceded by a '+'." 1>&2; exit 2;; ?) echo "$name: $OPTARG: bad option. Use -h for help." 1>&2; exit 2;; esac done # remove args that were options shift $((OPTIND-1)) if [ $# -lt 2 ]; then echo -e "$Usage\nUse -h for help." 1>&2 exit 2 fi case "$1" in -[0-9]*-|[0-9]*-) # Start value only count=${1%-} forever=1 end="-1"; ;; -[0-9]*-[0-9]*|[0-9]*-[0-9]*) # Start and end value s=${1%-} end=${s##[0-9]*-} count=${s%-$end} ;; -[0-9]*|[0-9]*) end=$1 case "$end" in -\*) count=-1;; esac ;; -) forever=1 end="-1"; ;; *) echo "$name: bad count parameter: $1" 1>&2 exit 1 ;; esac shift [ -z "$end" -o $count -le "$end" ] && increment=1 || increment=-1 istrue $verbose && echo "start=$count end=$end" 1>&2 # Need to do this here so that up to this point, -0 will keep the leading - # and end will not be 0 if no value assigned typeset -i end let end+=increment # make loop inclusive of original endcount while istrue $forever || [ $count -ne $end ]; do istrue $print && echo $count 1>&2 eval "$@" istrue $sleep && sleep $sleep let count+=increment done --- NEW FILE: cal2day.bash --- #!/bin/bash # cal2day - "parse" appropriate calendar output to match date number # with day name. # # usage: cal2day month day [year] # # ORIGINAL *TAG:33239 3:Dec 9 1997:0755:sh.d/cal2day: # # Obtained from usenet # # Converted to bash v2 syntax by Chet Ramey <ch...@po...> #1 PARSE OPTIONS while getopts :dls _inst do case $_inst in (d) format='%1d%.0s\n' ;; # 0, 1, ..., 7 (l) format='%0.s%-s\n' ;; # Sunday, Monday, ..., Saturday (s) format='%0.s%-.3s\n' ;; # Sun, Mon, ..., Sat esac done shift $((OPTIND-1)) #2 PARAMETER VALUES ((!$#)) && set -- $(date '+%m %d') : ${format:='%0.s%-.3s\n'} : ${1:?missing month parameter [1-12]} : ${2:?missing day parameter [1-31]} #3 CALCULATE DAY-OF-WEEK FROM DATE cal $1 ${3:-$(date +%Y)} | gawk -FX ' BEGIN { day="Sunday Monday Tuesday WednesdayThursday Friday Saturday" sub(/^0/, "", daynum) dayre="(^| )" daynum "( |$)" } #NR==2 { print length($0) } NR==1 || NR==2 \ { next } dayre { if (match($0, dayre)) { #print RSTART, RLENGTH, substr($0, RSTART, RLENGTH) if (daynum<=9 || RSTART==1) RSTART-=1 exit } } END { # 20/21 char width assumed printf format, RSTART/3, substr(day, RSTART*3+1, 9) } ' daynum=$2 format=$format - exit 0 --- NEW FILE: pmtop --- #! /bin/bash # # pmtop - poor man's `top' for SunOS 4.x # CLEAR=clear # could also be 'tput clear' HEADER="USER PID %CPU %MEM SZ RSS TT STAT START TIME COMMAND" if [ -n "$LINES" ]; then SS=$(( $LINES - 2 )) else SS=20 fi while : do $CLEAR echo "$HEADER" ps -aux | sort -nr -k 3 | sed ${SS}q sleep 5 done exit 0 --- NEW FILE: ncp --- #! /bin/bash # # original from: # @(#) ncp.ksh,nmv.ksh 1.1 94/07/23 # 92/01/18 john h. dubois iii (jo...@ar...) # 92/01/31 added check for no args left after shifts # 92/02/17 added help # 92/02/25 remove path component from filename before tacking it onto dest. # 92/03/15 exec mv or cp # 93/07/13 Added -i # 93/09/29 Made abort if file exists optional. # 93/11/19 Exit before invoking mv if no files to move # 94/01/03 Added o option # 94/04/13 Added x option. # Fixed appending of source filename, broken by earlier change. # 94/07/23 Append only the filename part of the source path. # # conversion to bash v2 syntax done by Chet Ramey false() { return 1 } true() { return 0 } phelp() { echo "$name: do a $cmd with extra checking and options. $Usage $name is used as a front end for $cmd to get the [icfo] options, and so that a trailing / will force the last component of the path to be interpreted as a directory, so that $name foo bar/ will fail if bar is not an existing directory, instead of changing the name of foo to bar. Effectively, $name foo bar/ is short for $name foo bar/foo Options: -h prints this help. -c checks first for the existence of each file, and fails if it exists. -i is like -c except that if the file exists and stdin and stdout are a tty, a query is printed and a reply is read; a file is overwritten only if the reply begins with 'y'. -f unsets -c and -i (in case $cmd is aliased to $name). -o (overwrite only) checks that the named file(s) exist and fails for any that do not. It is the complement of the -c option. Whichever of [cifo] comes later on the command line determines the behaviour. Any of these options must come before any standard $cmd options." } # interactive: Attempt to overwrite file should result in interactive # query rather than automatic failure. # noover: Do not overwrite files (if interactive is true, query, else fail) # overwrite: Only overwriting is allowed, not creation of new files. # debug: Print debugging info. typeset interactive=false noover=false overwrite=false debug=false name=${0##*/} case "$name" in ncp|nmv) cmd=/bin/${name#?} ;; *) echo "$name: Must be invoked as ncp or nmv." 1>&2 ; exit 2;; esac Usage="Usage: $name [-cfhio] $cmd-cmd-line" while getopts :cfhiox opt; do case $opt in h) phelp; exit 0;; x) debug=true ;; c) noover=true ;; i) noover=true ; interactive=true ;; f) noover=false ; interactive=false ;; o) overwrite=true ; noover=false ; interactive=false;; +?) echo "$name: options should not be preceded by a '+'." 1>&2; exit 2;; ?) echo "$name: $OPTARG: bad option. Use -h for help." 1>&2 ; exit 2;; esac done # remove args that were options shift $((OPTIND - 1)) if [ $# -lt 2 ]; then echo -e "$Usage\nUse -h for help." exit fi Check() { if [ ! -f "$1" ] && $overwrite; then echo "$name: $1: File does not exist." 1>&2 return 1 elif [ -f "$1" ] && $noover; then if [ $interactive = false ] || [ ! -t 0 ] || [ ! -t 1 ]; then echo "$name: $1: File exists." 1>&2 return 1 else while :; do echo -n \ "$name: $1: File exists. Overwrite? (y)es/(n)o/(a)bort/(Y)es for all: " 1>&2 read reply case "$reply" in y*) echo "$name: Overwriting $1." return 0 ;; Y*) echo "$name: Overwriting $1." interactive=false noover=false return 0 ;; [nN]*) echo "$name: Skipping $2." return 1 ;; [aA]*) echo "$name: Aborting." exit 1 ;; *) echo "$name: Invalid response." 1>&2 ;; esac done fi else return 0 fi } # i is the index of the filename being examined # lastarg is the index of the last filename before the dest directory name typeset -i i=0 lastarg=$(($#-1)) # Sets argv[0..$#-1] argv=("$@") $debug && echo argv = "${argv[@]}" 1>&2 dest=${argv[lastarg]} if $debug; then echo \ "interactive=$interactive noover=$noover overwrite=$overwrite debug=$debug lastarg=$lastarg dest=$dest name=$name cmd=$cmd files=$*" 1>&2 fi if $noover || $overwrite; then $debug && echo "checking for existance of directories..." 1>&2 # If the destination is not intended to be a directory... if [ $# -eq 2 ] && [ ! -d "$dest" ]; then Check "$dest" "$1" || exit 0 # No files to copy else while [ $i -lt $lastarg ]; do Check "$dest/${argv[i]##*/}" "${argv[i]}" || unset argv[i] let i+=1 done fi fi [ ${#argv[@]} -lt 2 ] && exit 0 # If only 2 args are given, mv/cp will not insist that the destination # be a directory, which we want if the destination ends in "/" or if # the original number of args was >2. # $# is still the original number of args. # Tack the file name onto the destination to force this behaviour. lastisslash() { case "$1" in */) return 0;; *) return 1;; esac } if [ ${#argv[@]} = 2 ] && { lastisslash "$2" || [ $# -gt 2 ]; }; then $debug && echo "Appending filename." 1>&2 # Don't know which element of argv[] holds the source filename, # since may have started with more than 1 source file & had some unset. # So, compact args to make it easy to find the set one. argv=("${argv[@]}") argv[1]="${argv[1]}/${argv[0]##*/}" fi $debug && echo "Executing command: $cmd ${argv[@]}" 1>&2 exec $cmd "${argv[@]}" --- NEW FILE: untar --- #! /bin/bash # # original from: # @(#) untar.ksh 1.0 93/11/10 # 92/10/08 john h. dubois iii (jo...@ar...) # 92/10/31 make it actually work if archive isn't in current dir! # 93/11/10 Added pack and gzip archive support # # conversion to bash v2 syntax done by Chet Ramey phelp() { echo \ "$name: extract tar archives into directories, uncompressing if neccessary. Usage: $name archive[.tar[.[Z|gz]]] .. If an archive name given does not end in .tar, .tar.Z, or .tar.gz, it is searched for first with .tar added, then .tar.Z, and then .tar.gz added. The real filename must end in either .tar, .tar.Z, or .tar.gz. A directory with the name of the archive is created in the current directory (not necessarily the directory that the archive is in) if it does not exist, and the the contents of the archive are extracted into it. Absolute pathnames in tarfiles are suppressed." } if [ $# -eq 0 ]; then phelp exit 1 fi name=${0##/} OWD=$PWD for file; do cd $OWD case "$file" in *.tar.Z) ArchiveName=${file%%.tar.Z} zcat=zcat;; *.tar.z) ArchiveName=${file%%.tar.z} zcat=pcat;; *.tar.gz) ArchiveName=${file%%.tar.gz} zcat=gzcat;; *) ArchiveName=$file for ext in "" .Z .z .gz; do if [ -f "$file.tar$ext" ]; then file="$file.tar$ext" break fi done if [ ! -f "$file" ]; then echo "$file: cannot find archive." 1>&2 continue fi ;; esac if [ ! -r "$file" ]; then echo "$file: cannot read." >&2 continue fi DirName=${ArchiveName##*/} [ -d "$DirName" ] || { mkdir "$DirName" || { echo "$DirName: could not make archive directory." 1>&2 continue } } cd $DirName || { echo "$name: cannot cd to $DirName" 1>&2 continue } case "$file" in /*) ;; *) file=$OWD/$file ;; esac echo "Extracting archive $file into directory $DirName..." case "$file" in *.tar.Z|*.tar.z|*.tar.gz) $zcat $file | tar xvf -;; *.tar) tar xvf $file;; esac echo "Done extracting archive $file into directory $DirName." done --- NEW FILE: shprof --- #! /bin/bash # # shprof - a line profiler for shell scripts # # adapted from a similar program included in `The New KornShell' by # Bolsky and Korn and posted to usenet by bsh...@ch... # # converted to bash v2 syntax by Chet Ramey # TMPFILE=${TMP:-/tmp}/shprof$$ trap 'rm -f $TMPFILE' EXIT errexit() { echo $0: "$@" >&2 exit 1 } # create script with profiling enabled cat > $TMPFILE <<- \_EOF_ declare -a _line _profend() { case "$1" in /*|./*) file="$1" ;; *) file=$(type -path "$1") ;; esac echo "*** line profile for $file ***" i=1; while read -r && [ $i -le $NLINE ]; do count=${_line[$i]} if [ "$count" -gt 0 ]; then echo "[$count] $i: $REPLY" fi i=$((i + 1)) done <$file _EOF_ # make the profiling script remove itself after printing line stats echo "rm -f $TMPFILE" >> $TMPFILE cat >> $TMPFILE <<- \_EOF_ } _command=$1 shift i=1 NLINE=$(wc -l < "$_command") while [ $i -le $NLINE ]; do _line[$i]=0 i=$((i + 1)) done unset i trap "_profend ${_command}" EXIT trap '_line[$LINENO]=$((${_line[$LINENO]} + 1))' DEBUG LINENO=0 _EOF_ case "$1" in /*|./*) file=$1 ;; *) file=$((type -path "$1")) ;; esac cat "${file-$1}" >> $TMPFILE || errexit "${1}: cannot open" chmod +x $TMPFILE exec -a "$file" $TMPFILE "$@" --- NEW FILE: uuenc --- #! /bin/bash # # original from: # @(#) uuenc.ksh 1.0 93/09/18 # 93/09/18 john h. dubois iii (jo...@ar...) # # conversion to bash v2 syntax by Chet Ramey istrue() { test 0 -ne "$1" } isfalse() { test 0 -eq "$1" } phelp() { echo "$name: uuencode files. $Usage For each filename given, $name uuencodes the file, using the final component of the file's path as the stored filename in the uuencoded archive and, with a .${SUF} appended, as the name to store the archive in. Example: $name /tmp/foo The file /tmp/foo is uuencoded, with \"foo\" stored as the name to uudecode the file into, and the output is stored in a file in the current directory with the name \"foo.${SUF}\". Options: -f: Normally, if the file the output would be stored in already exists, it is not overwritten and an error message is printed. If -f (force) is given, it is silently overwritten. -h: Print this help." } name=${0##*/} Usage="Usage: $name [-hf] <filename> ..." typeset -i force=0 SUF=uu while getopts :hf opt; do case $opt in h) phelp; exit 0;; f) force=1;; +?) echo "$name: options should not be preceded by a '+'." 1>&2 ; exit 2;; ?) echo "$name: $OPTARG: bad option. Use -h for help." 1>&2 ; exit 2;; esac done # remove args that were options shift $((OPTIND - 1)) if [ $# -lt 1 ]; then echo "$Usage\nUse -h for help." 1>&2 exit fi for file; do tail=${file##*/} out="$tail.${SUF}" if isfalse $force && [ -a "$out" ]; then echo "$name: $out: file exists. Use -f to overwrite." 1>&2 else uuencode $file $tail > $out fi done --- NEW FILE: frcp --- #! /bin/bash # # original from: # # @(#) frcp.ksh 2.2 93/11/14 # 92/06/29 john h. dubois iii (jo...@ar...) # 92/10/14 Cleaned up, improved, added -d and -r options # 92/11/11 Made work with a dest of '.' # 93/07/09 Added -l and -n options, & login as anonymous if no .netrc entry # 93/11/14 Use either passwd or password in .netrc, since ftp does. # # conversion to bash v2 syntax by Chet Ramey # # frcp: ftp front end with rcp-like syntax. # Note: requires any machine names given to be listed with # user and password in .netrc. If not, anonymous FTP is # done. # # full path to ftp binary if [ -x /usr/bin/ftp ]; then FTP=/usr/bin/ftp; elif [ -x /usr/ucb/ftp ]; then FTP=/usr/ucb/ftp else FTP=ftp fi istrue() { test 0 -ne "$1" } isfalse() { test 0 -eq "$1" } # For each filename given, put the filename in filename[n] # and the machine it is on in machine[n]. function SplitNames { typeset file typeset -i i=1 unset filename[*] machine[*] for file; do case "$file" in *:*) machine[i]=${file%%:*} ;; *) machine[i]=$LocalMach ;; esac filename[i]=${file#*:} let i+=1 done } function verboseprint { echo "$@" echo "$@" 1>&2 } function MakeDir { OFS=$IFS local IFS=/ dir component case "$1" in /*) ;; *) dir=. esac set -- $1 IFS=$OFS for component; do dir=$dir/$component if [ ! -d "$dir" ]; then if mkdir "$dir"; then :; else echo "Could not make directory $dir." >&2 return 1 fi fi done return 0 } lastisdot () { case "$1" in */.|*/..) return 0;; *) return 1;; esac } # CopyFiles: issue ftp(TC) commands to copy files. # Usage: CopyFiles [sourcemachine:]sourcepath ... [destmachine:]destpath # Global vars: # Uses LocalMach (should be name of local machine) # Sets global arrs machine[]/filename[] function CopyFiles { unset machine[*] filename[*] SplitNames "$@" # split names into filename[1..n] and machine[1..n] local DestMach=${machine[$#]} # Machine to copy files to local DestPath=${filename[$#]} # Destination file/dir unset machine[$#] filename[$#] [ -z "$DestPath" ] && DestPath=. # dest was given as machine: # Try to determine if destination should be a directory # so that it can be forced to be a directory. case "$DestPath" in */) ;; # don't add / if trailing / already present *) if [ $# -gt 2 ] || # if more than two args given, last must be a dir # If dest in on local machine, check whether it is a directory [ $DestMach = $LocalMach -a -d $DestPath ] || # If dest ends with . or .., it is a directory lastisdot "$DestPath" then DestPath=$DestPath/ fi ;; esac # If one of the above tests made us think dest is a directory, # but it isn't, complain case "$DestPath" in */) if [ "$DestMach" = "$LocalMach" ] && [ ! -d "$DestPath" ]; then echo "Destination is not a directory." 1>&2 exit 1 fi ;; esac DoCopy "$DestMach" "$DestPath" } # Usage: OpenMachine machine-name # Emits login sequence or doesn't, depending on .netrc file and global # variables anon and noanon OpenMachine () { local machine=$1 netrc=$HOME/.netrc user= password= if isfalse $anon && [ -r $netrc ]; then set -- $(gawk ' /machine (.* )?'"$machine"'($| )/,/^ *$/ { Fields[$1] = $2 if ("passwd" in Fields) Fields["password"] = Fields["passwd"] if ("login" in Fields && "password" in Fields) { print Fields["login"] " " Fields["password"] exit } } ' $netrc ) user=$1 password=$2 fi if [ -z "$password" ]; then if istrue $noanon; then echo "No .netrc entry for machine $machine" 1>&2 exit 1 fi user=anonymous password=$USER@$LocalMach fi verboseprint open $machine echo user $user "*******" 1>&2 echo user $user $password } # Usage: DoCopy destination-machine destination-path # Copies the files in global arrs machine[]/filename[] to the given dest # Global vars: # Uses machine[], filename[], LocalMach, check DoCopy () { local DestMach=$1 local DestPath=$2 local OpenMach # Machine that connection is currently open to local OWD=$PWD SourceMach SourceFile local FileName typeset -i i=1 while [ $i -le ${#machine[*]} ]; do istrue $check && verboseprint "runique" SourceMach=${machine[i]} SourceFile=${filename[i]} DestFile=$DestPath # if DestPath is a dir, # add source filename to it without source path case "$DestFile" in */) DestFile=$DestFile${SourceFile##*/} ;; esac if [ $SourceMach = $LocalMach ]; then if [ $DestMach != "$OpenMach" ]; then OpenMachine $DestMach OpenMach=$DestMach fi verboseprint put $SourceFile $DestFile elif [ $DestMach = $LocalMach ]; then if istrue $check && [ -f "$DestFile" ]; then echo "$DestFile already exists." 1>&2 continue fi # If destination is on local machine, # the dest will be a full dir/filename if istrue $createdirs; then MakeDir "${DestFile%/*}" || continue fi if [ $SourceMach != "$OpenMach" ]; then OpenMachine $SourceMach OpenMach=$SourceMach fi # If source filename has wildcards ([, ], *, ?) do an mget case "$SourceFile" in \[*\]|*\**|*\?*) verboseprint lcd "$DestFile" verboseprint mget "$SourceFile" verboseprint lcd $OWD ;; *) verboseprint get "$SourceFile" "$DestFile" ;; esac else echo "Neither source machine \"$SourceMach\" "\ "nor destination machine \"$DestMach\" is local." 1>&2 fi let i+=1 done } # Start of main program name=${0##*/} if [ "$1" = -h ]; then echo \ "$name: do ftp transfers using rcp-style parameters. Usage: $name <source> <destpath> or $name <source> [<source> ...] <destdir> At least one of <source> and <destpath> must be the local system. A remote filename is given as machinename:filename If remote filenames contain wildcards, they will be globbed on the remote machine. Make sure they are quoted when $name is invoked. If the invoking user's .netrc file (see ftp(TC)) contains an entry for the remote system with a login and password supplied, $name will log in using the given login and password. If not, $name will login in as user anonymous and with the user@localsystem as the password. Options: -c: check: do not overwrite files. -d: create directories as needed. -f: force: overwrite files (default). -h: print this help. -l: fail if there is no entry with login and password for the remote system, instead of logging in as anonymous. -n: log in as anonymous even if there is an entry for the remote system in the user's .netrc file. -r: read source/dest filename pairs from the standard input, one pair per line, and copy files accordingly." exit 0 fi typeset -i check=0 createdirs=0 readinput=0 anon=0 noanon=0 while getopts :cdflnr Option do case "$Option" in c) check=1;; d) createdirs=1;; f) check=0;; l) noanon=1;; n) anon=1;; r) readinput=1;; \?) echo "$OPTARG: invalid option."; exit 1;; esac done shift $((OPTIND-1)) LocalMach=`hostname` if istrue $readinput; then while read line; do CopyFiles $line done | $FTP -nv else if [ $# -lt 2 ]; then echo "$name: Not enough arguments. Use -h for help." 1>&2 exit fi CopyFiles "$@" | $FTP -nv fi --- NEW FILE: fman --- #! /bin/bash # # original from: # fman: new man program # @(#) fman.ksh 1.5 94/04/16 # 91/07/03 john h. dubois iii (jo...@ar...) # 91/07/11 made it unpack man pages if neccessary # 91/07/16 fixed test for whether man file pattern was expanded # 92/01/21 made it read /etc/default/man to get section order, # and only display the first section found. # 92/02/06 changed name to fman # 92/02/07 fixed bug in notfound # 92/02/13 incorporated changes from DOS version # 92/03/11 changed to use MANPATH from environment if set, # and search all directories given in MANPATH # 92/03/15 exec pager or man w/o forking # 92/05/31 try using index if one exists # 92/10/01 Added "See also <other sections>" # 92/10/18 If PAGER is less, search for name of man page to make it easier # to find information in man pages for multiple items # 92/11/11 Make it work for compressed files not listed in index; # deal with man pages listed in index that don't exist. # 93/03/30 Fixed bug in MANPATH processing # 93/06/17 Include paths in "See also:" message if they would be needed # to get to a man page. Allow MANPATH spec on command line. # 93/07/09 Added -h and -e options. # 94/04/16 Added x option. # # conversion to bash v2 syntax done by Chet Ramey istrue() { test 0 -ne "$1" } isfalse() { test 0 -eq "$1" } # Finds all sections that man page $1 is in and puts them in the the # global array Sections[]. # The filename of each page is put in FileNames[] with the same index. # Global vars used: # patharr[] MANPATH directories. FindSectionsInIndex () { typeset index indexes section mpath page=$1 typeset -i i=0 NIndex=0 for mpath in "${patharr[@]}"; do if [ -r $mpath/index ]; then indexes="$indexes $mpath/index" let NIndex+=1 fi done [ -z "$indexes" ] && return # Make egrep give filename [ NIndex -lt 2 ] && indexes="$indexes /dev/null" # set positional parameters to # indexfile:searchname pagename section ... # e.g. # /usr/man/index:FP_OFF Routines DOS set -- `egrep "^$page[ ]" $indexes` while [ $# -gt 2 ]; do FileNames[i]=${1%%index*}cat$3/$2.$3 Sections[i]=$3 shift 3 let i+=1 done } # Finds all sections that man page $1 is in by searching each man directory # in the order given in patharr[], # and puts them in the the global array Sections[]. # The filename of each page is put in FileNames[] with the same index. # Global vars used: # patharr[] MANPATH directories. FindSectionsInDirs () { local page=$1 mpath AllPaths Path typeset -i i for mpath in "${patharr[@]}"; do AllPaths="$AllPaths $mpath/cat[0-9]*/$page.* $mpath/man[0-9]*/$page.*" done i=0 for Path in $AllPaths; do istrue $debug && echo Path = $Path case "$Path" in *\*) ;; *) # Remove compressed-file suffix to make FileNames be the same # as it is when built by FindSectionsInIndex() FileNames[i]=${Path%.[zZ]} Path=${Path%/*} Sections[i]=${Path##*/*.} let i+=1 ;; esac done } # FindSection: display man page. # Uses ordarr[] (built from $ORDER) to display the version of the man # page that occurs first in $ORDER. # Sections[] gives the sections that a man page was found in. # If the global variable "exist" is set to 1, nothing is displayed; # the function instead returns zero if a page is found, nonzero if not. # The filename of each page is in FileNames[] with the same index. # Global vars used: # Sections[], FileNames[], ordarr[] FindSection () { typeset -i NumPages i foundsec local section OtherSec filename NPAGER=$PAGER POpt page=$1 Pat local PageFile NumPages=${#Sections[*]} # Number of versions of man page found. isfalse $NumPages && return 1 case "$PAGER" in *less) Popt="-p$page" ;; esac # For each section in ORDER, determine if any man page was found in # that section for section in "${ordarr[@]}"; do i=0 foundsec=0 while [ $i -lt $NumPages ]; do if [ "${Sections[i]}" = $section ]; then # Found a man page from this section of ORDER filename=${FileNames[i]} if [ -z "$PageFile" ]; then PageFile=$filename else if istrue $foundsec; then OtherSec="$OtherSec$page(${filename%/*/*} $section) " else OtherSec="$OtherSec$page($section) " fi fi foundsec=1 istrue $exist && return fi let i+=1 done done # No pages with the specified section found. [ -z "$PageFile" ] && return 1 # Return if all we want to know is whether the man page exists. [ "$exist" = 1 ] && return 0 if [ -z "$OtherSec" ]; then NPAGER="exec $PAGER" fi if [ -r $PageFile ]; then $NPAGER $POpt $PageFile elif [ -r $PageFile.z ]; then pcat $PageFile.z | $NPAGER $POpt elif [ -r $PageFile.Z ]; then zcat $PageFile.Z | $NPAGER $POpt elif [ -f $PageFile.gz ]; then gzip -dc $PageFile.gz | $NPAGER $POpt else echo "$PageFile: cannot open." 1>&2 OtherSec= unset Sections[i] let i+=1 continue fi echo "See also $OtherSec" exit 0 } phelp() { echo "$name: print man pages. $name locates and prints the specified manual pages from the online UNIX documentation. $Usage Options: -e: Determine whether the specified man page exists. Nothing is printed; $0 exits with a zero status if the page exists and a nonzero status if it does not. -h: Print this help." } # main program typeset -i exist=0 debug=0 name=${0##*/} Usage="Usage: $name [-eh] [[manpath] section] command-name" while getopts :hex opt; do case $opt in h) phelp; exit 0;; e) exist=1 ;; x) debug=1 ;; +?) echo "$name: options should not be preceded by a '+'." 1>&2; exit 2;; ?) echo "$name: $OPTARG: bad option. Use -h for help." 1>&2 ; exit 2 ;; esac done # remove args that were options shift $((OPTIND-1)) if [ $# -lt 1 ]; then echo -e "$Usage\nUse -h for help." 1>&2 exit fi P=$PAGER O=1:n:l:6:8:2:3:4:5:7:p:o T=$TERM M=${MANPATH:-/usr/local/man:/usr/man} [ -f /etc/default/man ] && . /etc/default/man [ -n "$P" ] && PAGER=$P [ -n "$O" ] && ORDER=$O [ -n "$T" ] && TERM=$T [ -n "$M" ] && MANPATH=$M case $# in 0) echo "No man page specified." ; exit 1;; 1) page=$1;; 2) ORDER=$(echo $1 | tr a-z A-Z) ; page=$2;; 3) MANPATH=$1 [ -n "$2" ] && ORDER=$(echo $2 | tr a-z A-Z) page=$3;; *) echo "Too many arguments."; exit 1;; esac aargs=("$@") [ ! -t 0 ] && PAGER=cat OIFS=$IFS IFS=: patharr=($MANPATH) i=0 for d in $MANPATH; do for sec in $ORDER; do ordarr[i]=$d/cat${sec} let i+=1 ordarr[i]=$d/man${sec} let i+=1 done done IFS=$OIFS istrue $debug && echo patharr = "${patharr[@]}" # if less or more is being used, remove multiple blank lines export LESS="-s $LESS" export MORE="-s $MORE" # Try using index FindSectionsInIndex "$page" # Exit 0 if a page was found and we're just testing for existence. FindSection "$page" && exit 0 # Try searching directories unset Sections[*] FindSectionsInDirs "$page" FindSection "$page" && exit 0 istrue $exist && exit 1 # Try using man # If using more or less, make man run faster by letting more or less compress # multiple blank lines instead of rmb #case "$PAGER" in #*more|*less) manopt=-b;; #esac #cmd=(man $manopt -p$PAGER "${aargs[@]}") export PAGER cmd=(man $manopt "${aargs[@]}") istrue $debug && echo "$name: running ${cmd[*]}" 1>&2 exec "${cmd[@]}" --- NEW FILE: bashrand --- #! /bin/bash # bashrand - generate a random number in a specified range with an # optionally specified ``seed'' value. # # Original Author: Peter Turnbull, May 1993 usage() { echo "$PROG: usage: $PROG [-s seed] lower-limit upper-limit" >&2 } PROG=${0##*/} SEED=$$ # Initialize random-number seed value with PID while getopts s: opt do case "$opt" in s) SEED=$OPTARG ;; *) usage ; exit 2 ;; esac done shift $((OPTIND - 1)) # Process command-line arguments: case $# in 2) Lower=$1; Upper=$2 ;; *) usage ; exit 2 ;; esac # Check that specified values are integers: expr "$Lower" + 0 >/dev/null 2>&1 || { echo "$PROG: lower ($Lower) not an integer" >&2 exit 1 } expr "$Upper" + 0 >/dev/null 2>&1 || { echo "$PROG: upper ($Upper) not an integer" >&2 exit 1 } expr "$SEED" + 0 >/dev/null 2>&1 || { echo "$PROG: seed ($SEED) not an integer" >&2 exit 1 } # Check that values are in the correct range: (( $Lower < 0 )) || [ `expr "$Lower" : '.*'` -gt 5 ] && { echo "$PROG: Lower limit ($Lower) out of range" >&2 exit 1 } (( $Upper > 32767 )) || [ `expr "$Upper" : '.*'` -gt 5 ] && { echo "$PROG: Upper limit ($Upper) out of range" >&2; exit 1 } (( $SEED < 0 )) || (( $SEED > 32767 )) || [ `expr "$SEED" : '.*'` -gt 5 ] && { echo "$PROG: Seed value ($SEED) out of range (0 to 32767)" >&2 exit 1 } (( $Upper <= $Lower )) && { echo "$PROG: upper ($Upper) <= lower value ($Lower)" >&2 exit 1 } # Seed the random-number generator: RANDOM=$SEED # Compute value, scaled within range: let rand="$RANDOM % ($Upper - $Lower + 1) + $Lower" # Report result: echo $rand --- NEW FILE: pf --- #! /bin/bash # # original from: # # @(#) p.ksh 1.1 93/11/09 # p: page compressed & plain files in the order given # 92/01/23 john h. dubois iii (jo...@ar...) # 92/02/14 changed incorrect zpack to pcat # 92/02/16 added help # 92/10/11 search for file.Z and file.z if file not found # 92/10/18 pass options to pager # 93/11/09 Understand gzipped files too # Wait after printing message about unreadable files # Make less prompt include name of file being uncompressed # # conversion to bash v2 by Chet Ramey; renamed to pf # DefPager=/local/bin/less istrue() { test 0 -ne "$1" } warn() { echo "$@" 1>&2 } if [ "$1" = -h ]; then echo \ "$0: page a file. Usage: $0 [pager-option ...] [filename ...] Files are paged by the program specified in the user's PAGER environment variable, or by $DefPager if PAGER is not set. If no filename is given, text to page is read from the standard input. If filenames are given, they are either paged directly, or unpacked/ uncompressed and then paged. Files are assumed to be in packed, compressed, or gzipped format if the filename ends in .Z, .z, or .gz respectively. If a filename that does not end in .Z, .z, or .gz is not found, it is searched for with one of those extensions attached. Each group of plain files is paged by a single instance of the pager. Each packed or compressed file is paged by a separate instance of the pager. Initial arguments beginning with + or - are taken to be pager options and are passed to each instance of the pager. If a pager option takes a value it should be given with the option as a single argument (with no space between the option and the value)." exit 0 fi # Get pager options while [ $# -gt 0 ]; do case "$1" in -*|+*) Opts="$Opts $1" ; shift;; *) break;; esac done [ -z "$PAGER" ] && PAGER=$DefPager # Read from stdin [ $# = 0 ] && exec $PAGER $Opts typeset -i filenum=0 badfile=0 for file; do if [ ! -r "$file" ]; then case "$file" in *.[Zz]|*.gz) # Check if user specified a compressed file without giving its extension for ext in Z z gz; do if [ -r "$file.$ext" ]; then file="$file.$ext" break fi done;; esac fi if [ ! -r "$file" ]; then warn "$file: cannot read." badfile=1 else files[filenum]=$file let filenum+=1 fi done if istrue $badfile && [ $filenum -gt 0 ]; then echo -n "Press return to continue..." 1>&2 read fi unset plain for file in "${files[@]}"; do case "$file" in *.[zZ]|*.gz) set -- Z zcat z pcat gz gzcat # Find correct uncompression program while [ $# -gt 0 ]; do case "$file" in *.$1) # Page any uncompressed files so that they will be read # in the correct order [ ${#plain[@]} -gt 0 ] && $PAGER $Opts "${plain[@]}" unset plain[*] # If page is less, set the prompt to include the name of # the file being uncompressed. Escape the . in the extension # because less treats is specially in prompts (other dots # in filenames will still be mucked with). case "$PAGER" in *less) Prompt="-P[${file%.$1}\\.$1] (%pb\\%)" ;; *) unset Prompt ;; esac $2 "$file" | $PAGER "$Prompt" $Opts break esac shift 2 done ;; *) plain[${#plain[@]}]=$file;; esac done # Page any uncompressed files that haven't been paged yet [ ${#plain[@]} -gt 0 ] && exec $PAGER $Opts "${plain[@]}" --- NEW FILE: lowercase --- #! /bin/bash # # original from # @(#) lowercase.ksh 1.0 92/10/08 # 92/10/08 john h. dubois iii (jo...@ar...) # # conversion to bash v2 syntax done by Chet Ramey Usage="Usage: $name file ..." phelp() { echo "$name: change filenames to lower case. $Usage Each file is moved to a name with the same directory component, if any, and with a filename component that is the same as the original but with any upper case letters changed to lower case." } name=${0##*/} while getopts "h" opt; do case "$opt" in h) phelp; exit 0;; *) echo "$Usage" 1>&2; exit 2;; esac done shift $((OPTIND - 1)) for file; do filename=${file##*/} case "$file" in */*) dirname=${file%/*} ;; *) dirname=. ;; esac nf=$(echo $filename | tr A-Z a-z) newname="${dirname}/${nf}" if [ "$nf" != "$filename" ]; then mv "$file" "$newname" echo "$0: $file -> $newname" else echo "$0: $file not changed." fi done --- NEW FILE: uudec --- : # @(#) uudec.sh 1.0 93/11/22 # 92/08/04 jo...@ar... (John H. DuBois III) # 93/11/22 Added help. isfalse() { test 0 -eq "$1" } phelp() { "$name: process uuencoded files. Usage: uudec [-h] filename ... Options: -h: Print this help." } name=${0##*/} typeset -i force=0 while getopts "hf" opt; do case "$opt" in h) phelp; exit 0;; f) force=1;; *) echo "$Usage" 1>&2; exit 2;; esac done shift $((OPTIND - 1)) for file; do echo "$file" while read b mode filename && [ "$b" != begin ]; do :; done < "$file" if [ "$b" = begin ]; then if [ -f "$filename" ] && isfalse $force; then echo "Output file \"$filename\" exists. Not written." else uudecode "$file" fi else echo "No begin line." fi done --- NEW FILE: PERMISSION --- >From sp...@ar... Wed May 10 10:21:11 1995 Flags: 10 Return-Path: sp...@ar... Received: from po.cwru.edu (ro...@po... [129.22.4.2]) by odin.INS.CWRU.Edu with ESMTP (8.6.10+cwru/CWRU-2.1-ins) id KAA22876; Wed, 10 May 1995 10:21:10 -0400 (from sp...@ar... for <ch...@od...>) Received: from deepthought.armory.com (mm...@de... [192.122.209.42]) by po.cwru.edu with SMTP (8.6.10+cwru/CWRU-2.3) id BAA16354; Wed, 10 May 1995 01:33:22 -0400 (from sp...@ar... for <ch...@po...>) From: John DuBois <sp...@ar...> Date: Tue, 9 May 1995 22:33:12 -0700 In-Reply-To: Chet Ramey <ch...@od...> "ksh scripts" (May 9, 1:36pm) X-Www: http://www.armory.com/~spcecdt/ X-Mailer: Mail User's Shell (7.2.5 10/14/92) To: ch...@po... Subject: Re: ksh scripts Message-ID: <950...@de...> Sure. The canonical versions are available on ftp.armory.com; you might want to pick up the latest versions before modifying them. John On May 9, 1:36pm, Chet Ramey wrote: } Subject: ksh scripts } From odin.ins.cwru.edu!chet Tue May 9 10:39:51 1995 } Received: from odin.INS.CWRU.Edu by deepthought.armory.com id aa22336; } 9 May 95 10:39 PDT } Received: (chet@localhost) by odin.INS.CWRU.Edu (8.6.10+cwru/CWRU-2.1-ins) } id NAA20487; Tue, 9 May 1995 13:39:24 -0400 (from chet) } Date: Tue, 9 May 1995 13:36:54 -0400 } From: Chet Ramey <ch...@od...> } To: jo...@ar... } Subject: ksh scripts } Cc: ch...@od... } Reply-To: ch...@po... } Message-ID: <950...@od...> } Read-Receipt-To: ch...@po... } MIME-Version: 1.0 } Content-Type: text/plain; charset=us-ascii } Status: OR } } Hi. I'm the maintainer of bash (the GNU `Bourne Again shell') for } the FSF. } } I picked up a tar file of ksh scripts you wrote from an anon FTP site } a while back. I'd like your permission to include modified versions } of some of them in the next major bash distribution (with proper credit } given, of course). Is it OK if I do that? } } Chet Ramey } } -- } ``The lyf so short, the craft so long to lerne.'' - Chaucer } } Chet Ramey, Case Western Reserve University Internet: ch...@po... }-- End of excerpt from Chet Ramey --- NEW FILE: corename --- #! /bin/bash # # original from: # @(#) corename.ksh 1.0 93/04/01 # 92/11/11 john h. dubois iii (jo...@ar...) # 92/02/16 Added help option. # 92/02/22 Added cd to origdir to fix prob w/multiple relative paths. # 93/04/01 Added check for whether file exists. # # conversion to bash v2 syntax done by Chet Ramey # inspired by belal's equivalent utility if [ "$1" = -h ]; then echo \ "$0: print the names of executables that dumped core. Usage: $0 [corename ...] If no corename is given, \"core\" is assumed." exit 0 fi [ $# = 0 ] && set core origdir=$PWD for i; do cd $origdir file=${i##*/} dir=${i%$file} [ -z "$dir" ] && dir=$origdir/ if [ ! -f $dir$file ]; then echo "$dir$file: No such file." continue fi if [ ! -r $dir$file ]; then echo "$dir$file: Cannot open." continue fi cd $dir # the adb output syntax is highly variable. this works on SunOS 4.x set -- $(adb $file < /dev/null 2>&1 | sed 1q) name=${7#??} echo "$i: ${name%??}" done --- NEW FILE: pages --- #! /bin/bash # # original from: # @(#) pages.sh 1.0 92/09/26 # 92/09/05 John H. DuBois III (jh...@ar...) # 92/09/26 Added help # # conversion to bash v2 syntax by Chet Ramey Usage="$0 [-h] [-n lines/page] page-ranges [file ...]" usage() { echo "$Usage" 1>&2 } phelp() { echo "$0: print selected pages. Usage: $Usage If no file names are given, the standard input is read. The input is grouped into pages and a selected subset of them is printed. Formfeeds are acted on correctly. If the output device does automatic line wrap, lines that longer than the width of the output device will result in incorrect output. The first non-option argument is a list of pages to print. Pages are given as a list of ranges separated by commas. A range is either one number, two numbers separted by a dash, or one number followed by a dash. A range consisting of one number followed by a dash extends to the end of the document. Options: -n sets the number of lines per page to n. The default is 66." } while getopts "n:h" opt; do case "$opt" in n) LinesPerPage=$OPTARG;; h) phelp; exit 0;; *) usage; exit 2;; esac done shift $(($OPTIND - 1)) if [ $# -eq 0 ]; then echo $0: no page ranges given. 1>&2 usage exit 1 fi PageList=$1 shift gawk " BEGIN { PageList = \"$PageList\"; LinesPerPage = \"$LinesPerPage\""' if (LinesPerPage == "") LinesPerPage = 66 else if (LinesPerPage !~ "[1-9][0-9]*") ErrExit("Bad value for lines per page: " LinesPerPage) LinesPerPage += 0 NumRanges = split(PageList,Ranges,",") for (i = 1; i <= NumRanges; i++) { if ((StartRange = EndRange = Ranges[i]) !~ "^[0-9]+(-([0-9]+)?)?$") ErrExit("Bad range \"" StartRange "\"") sub("-.*","",StartRange) sub(".*-","",EndRange) if (EndRange == "") EndRange = 2 ^ 30 # Force StartRange and EndRange to be numeric values if ((StartRange += 0) == 0 || (EndRange += 0) == 0) ErrExit("Invalid page number \"0\" in range " Ranges[i]) if (StartRange > EndRange) ErrExit("Start page comes after end page in range " Ranges[i]) TmpRangeStarts[i] = StartRange TmpRangeEnds[i] = EndRange } # Sort ranges qsort(TmpRangeStarts,k) RangeEnds[0] = 0 for (i = 1; i <= NumRanges; i++) { RangeEnds[i] = TmpRangeEnds[k[i]] if ((RangeStarts[i] = TmpRangeStarts[k[i]]) <= RangeEnds[i - 1]) ErrExit("Overlapping ranges: " Ranges[k[i]] "," Ranges[k[i - 1]]) } RangeNum = LineNum = PageNum = 1 InRange = In(PageNum,RangeStarts[RangeNum],RangeEnds[RangeNum]) FS = "\014" } { if (LineNum > LinesPerPage) NewPage() if (InRange) printf "%s",$1 # Deal with formfeeds for (i = 2; i <= NF; i++) { if (InRange) printf "\014" NewPage() if (InRange) printf "%s",$i } if (InRange) print "" LineNum++ } function NewPage() { PageNum++ LineNum = 1 # At the start of each page, check whether we are in a print range WereInRange = InRange InRange = In(PageNum,RangeStarts[RangeNum],RangeEnds[RangeNum]) # If last page was in range and we no longer are, move to next range if (WereInRange && !InRange && ++RangeNum > NumRanges) exit } function In(a,Min,Max) { return (Min <= a && a <= Max) } function ErrExit(S) { print S > "/dev/stderr" Err = 1 exit 1 } # Arr is an array of values with arbitrary indices. # Array k is returned with numeric indices 1..n. # The values in k are the indices of array arr, # ordered so that if array arr is stepped through # in the order arr[k[1]] .. arr[k[n]], it will be stepped # through in order of the values of its elements. # The return value is the number of elements in the array (n). function qsort(arr,k, ArrInd,end) { end = 0 for (ArrInd in arr) k[++end] = ArrInd; qsortseg(arr,k,1,end); return end } function qsortseg(arr,k,start,end, left,right,sepval,tmp,tmpe,tmps) { # handle two-element case explicitely for a tiny speedup if ((end - start) == 1) { if (arr[tmps = k[start]] > arr[tmpe = k[end]]) { k[start] = tmpe k[end] = tmps } return } left = start; right = end; sepval = arr[k[int((left + right) / 2)]] # Make every element <= sepval be to the left of every element > sepval while (left < right) { while (arr[k[left]] < sepval) left++ while (arr[k[right]] > sepval) right-- if (left < right) { tmp = k[left] k[left++] = k[right] k[right--] = tmp } } if (left == right) if (arr[k[left]] < sepval) left++ else right-- if (start < right) qsortseg(arr,k,start,right) if (left < end) qsortseg(arr,k,left,end) } ' "$@" --- NEW FILE: cdhist.bash --- #! /bin/bash # # cdhist - cd replacement with a directory stack like pushd/popd # # usage: cd [-l] [-n] [-] [dir] # # options: # -l print the cd directory stack, one entry per line # - equivalent to $OLDPWD # -n cd to nth directory in cd directory stack # -s cd to first directory in stack matching (substring) `s' # # arguments: # dir cd to dir and push dir onto the cd directory stack # # If the new directory is a directory in the stack and the options selected # it (-n, -s), the new working directory is printed # # If the variable CDHISTFILE is set, the cd directory stack is loaded from # and written to $CDHISTFILE every time `cd' is executed. # # Note: I got this off the net somewhere; I don't know the original author # # Chet Ramey # ch...@po... _cd_print() { echo -e "$@" } cd() { typeset -i cdlen i typeset t if [ $# -eq 0 ] then set -- $HOME fi if [ "$CDHISTFILE" -a -r "$CDHISTFILE" ] # if directory history exists then typeset CDHIST i=-1 while read -r t # read directory history file do CDHIST[i=i+1]=$t done <$CDHISTFILE fi if [ "${CDHIST[0]}" != "$PWD" -a "$PWD" != "" ] then _cdins # insert $PWD into cd history fi cdlen=${#CDHIST[*]} # number of elements in history case "$@" in -) # cd to new dir if [ "$OLDPWD" = "" ] && ((cdlen>1)) then '_cdprint' ${CDHIST[1]} builtin cd ${CDHIST[1]} pwd else builtin cd "$@" # pwd fi ;; -l) # _cdprint directory list ((i=cdlen)) while (((i=i-1)>=0)) do num=$i '_cdprint' "$num ${CDHIST[i]}" done return ;; -[0-9]|-[0-9][0-9]) # cd to dir in list if (((i=${1#-})<cdlen)) then '_cdprint' ${CDHIST[i]} builtin cd ${CDHIST[i]} pwd else builtin cd $@ # pwd fi ;; -*) # cd to matched dir in list t=${1#-} i=1 while ((i<cdlen)) do case ${CDHIST[i]} in *$t*) '_cdprint' ${CDHIST[i]} builtin cd ${CDHIST[i]} pwd break ;; esac ((i=i+1)) done if ((i>=cdlen)) then builtin cd $@ # pwd fi ;; *) # cd to new dir builtin cd $@ # pwd ;; esac _cdins # insert $PWD into cd history if [ "$CDHISTFILE" ] then cdlen=${#CDHIST[*]} # number of elements in history i=0 while ((i<cdlen)) do echo ${CDHIST[i]} # update directory history ((i=i+1)) done >$CDHISTFILE fi } _cdins() # insert $PWD into cd history { # meant to be called only by cd typeset -i i i=0 while (( i < ${#CDHIST[*]} )) # see if dir is already in list do if [ "${CDHIST[$i]}" = "$PWD" ] then break fi ((i=i+1)) done if (( i>22 )) # limit max size of list then i=22 fi while (((i=i-1)>=0)) # bump old dirs in list do CDHIST[i+1]=${CDHIST[i]} done CDHIST[0]=$PWD # insert new directory in list } # examples shopt -s expand_aliases # go to known place before doing anything cd / echo CDHIST: "${CDHIST[@]}" for dir in /tmp /bin - -2 -l do cd $dir echo CDHIST: "${CDHIST[@]}" echo PWD: $PWD done exit 0 --- NEW FILE: ren --- #!/bin/bash #@ This program came from: ftp://ftp.armory.com/pub/scripts/ren #@ Look there for the latest version. #@ If you don't find it, look through http://www.armory.com/~ftp/ # # @(#) ren 2.1.1 2002-03-17 # 1990-06-01 John H. DuBois III (jo...@ar...) # 1991-02-25 Improved help info # 1992-06-07 Remove quotes from around shell pattern as required by new ksh # 1994-05-10 Exit if no globbing chars given. # 1995-01-23 Allow filename set to be given on command line. # 1997-09-24 1.4 Let [] be used for globbing. Added x option. # 1997-11-26 1.4.1 Notice if the sequences of globbing chars aren't the same. # 1999-05-13 Changed name to ren to avoid conflict with /etc/rename # 2000-01-01 1.4.2 Let input patterns that contain whitespace be used. # 2001-02-14 1.5 Better test for whether old & new globbing seqs are identical. # 2001-02-20 1.6 Added pP options. # 2001-02-27 1.7 Added qf options. Improved interpretation of rename patterns. # 2001-05-10 1.8 Allow multiple pP options. Added Qr options. # 2001-07-25 2.0 Added mz options. # 2001-11-25 2.1 Allow segment ranges to be given with -m. Work under ksh93. # 2002-03-17 2.1.1 Fixed bug in test for legal expressions. # todo: It would be nice to be able to escape metacharacters with '\' # todo: Should enhance patterns to make ] in a pair of brackets work ([]]) # todo: Allow use of all ksh globbing patterns. # todo: Allow use of extended regexps, with () to enumerate pieces and \num to # todo: select them. # # Modifications for bash made by Chet Ramey <ch...@po...> name=${0##*/} Usage="Usage: $name [-fhqtv] [-m<segstart[:segend]=operation>] [-z<len>] [-[pP]<pattern>] oldpattern [newpattern [filename ...]] or $name -r [same options as above] oldpattern newpattern directory ..." tell=false verbose=false warn=true warnNoFiles=true debug=false recurse=false inclPat= exclPat= declare -i inclCt=0 exclCt=0 check=true declare -i j op_end_seg # Begin bash additions shopt -s extglob # # ksh print emulation # # print [-Rnprsu[n]] [-f format] [arg ...] # # - end of options # -R BSD-style -- only accept -n, no escapes # -n do not add trailing newline # -p no-op (no coprocesses) # -r no escapes # -s print to the history file # -u n redirect output to fd n # -f format printf "$format" "$@" # print() { local eflag=-e local nflag= fflag= c local fd=1 OPTIND=1 while getopts "fRnprsu:" c do case $c in R) eflag= ;; r) eflag= ;; n) nflag=-n ;; s) sflag=y ;; f) fflag=y ;; u) fd=$OPTARG ;; p) ;; esac done shift $(( $OPTIND - 1 )) if [ -n "$fflag" ]; then builtin printf "$@" >&$fd return fi case "$sflag" in y) builtin history -s "$*" ;; *) builtin echo $eflag $nflag "$@" >&$fd esac } # End bash additions while getopts :htvxp:P:fqQrm:z: opt; do case $opt in h) print -r -- \ "$name: rename files by changing parts of filenames that match a pattern. $Usage oldpattern and newpattern are subsets of sh filename patterns; the only globbing operators (wildcards) allowed are ?, *, and []. All filenames that match oldpattern will be renamed with the filename characters that match the constant (non-globbing) characters of oldpattern changed to the corresponding constant characters of newpattern. The characters of the filename that match the globbing operators of oldpattern will be preserved. Globbing operators in oldpattern must occur in the same order in newpattern; for every globbing operators in newpattern there must be an identical globbing operators in oldpattern in the same sequence. Both arguments should be quoted since globbing operators are special to the shell. If filenames are given, only those named are acted on; if not, all filenames that match oldpattern are acted on. newpattern is required in all cases except when -m is given and no further arguments are given. If you are unsure whether a $name command will do what you intend, issue it with the -t option first to be sure. Examples: $name \"/tmp/foo*.ba.?\" \"/tmp/new*x?\" All filenames in /tmp that match foo*.ba.? will have the \"foo\" part replaced by \"new\" and the \".ba.\" part replaced by \"x\". For example, /tmp/fooblah.ba.baz would be renamed to /tmp/newblahxbaz. $name \* \*- foo bar baz foo, bar, and baz will be renamed to foo-, bar-, and baz-. $name '????????' '???... [truncated message content] |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:35
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/examples/obashdb In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/examples/obashdb Added Files: PERMISSION README bashdb bashdb.fns bashdb.pre Log Message: Pristine source --- NEW FILE: README --- This is a modified version of the Korn Shell debugger from Bill Rosenblatt's `Learning the Korn Shell', published by O'Reilly and Associates (ISBN 1-56592-054-6). The original `kshdb' is available for anonymous FTP with the URL ftp://ftp.uu.net/published/oreilly/nutshell/ksh/ksh.tar.Z --- NEW FILE: bashdb --- # kshdb - Korn Shell Debugger main file # adapted from 'Learning the Korn Shell' by Bill Rosenblatt (O'Reilly) # by Cigy Cyriac (ci...@fe...) # Main driver: constructs full script (with preamble) and runs it echo 'Bourne-Again Shell Debugger version 0.1' _pname=${0##*/} [ $# -eq 0 ] && { echo "${_pname}: usage: ${_pname} <script_file>" exit 1 } _guineapig=$1 [ -r $_guineapig ] || { echo "${_pname}: cannot read $_guineapig." >&2 exit 1 } shift _tmpdir=/tmp _libdir=. _dbgfile=$_tmpdir/bashdb$$ #temp file for script being debugged cat $_libdir/bashdb.pre $_guineapig > $_dbgfile if [ -f "$BASH" ]; then exec $BASH $_dbgfile $_guineapig $_tmpdir $_libdir "$@" else exec bash $_dbgfile $_guineapig $_tmpdir $_libdir "$@" fi # end of bashdb --- NEW FILE: bashdb.fns --- # bashdb.fns - Bourne-Again Shell Debugger functions _BUFSIZ=100 # Here after each statement in script being debugged. # Handle single-step and breakpoints. _steptrap() { let _curline=$1-1 # no. of line that just ran let "$_curline < 1" && let _curline=1 let "$_curline > $_firstline+$_BUFSIZ" && _readin $_curline let " $_trace" && _msg "$PS4, line $_curline: ${_lines[$(($_curline-$_firstline+1))]}" # if in step mode, decrement counter let " $_steps >= 0" && let _steps="$_steps - 1" # first check if line num or string brkpt. reached if _at_linenumbp || _at_stringbp; then _msg "Reached breakpoint at line $_curline" _cmdloop # enter debugger # if not, check whether break condition exists and is true elif [ -n "$_brcond" ] && eval $_brcond; then _msg "Break condition $_brcond true at line $_curline" _cmdloop # enter debugger # next, check if step mode and no. of steps is up elif let "$_steps == 0"; then _msg "Stopped at line $_curline" _cmdloop # enter debugger fi } # Debugger command loop. # Here at start of debugger session, when brkpt. reached, or after single-step. _cmdloop() { local cmd args # added support for default command (last one entered) while read -e -p "bashdb> [$lastcmd $lastargs] " cmd args; do if [ -z "$cmd" ]; then cmd=$lastcmd args=$lastargs fi lastcmd="$cmd" lastargs=$args # made commands to be debugger commands by default, no need for '*' prefix case $cmd in bp ) _setbp $args ;; #set brkpt at line num or string bc ) _setbc $args ;; # set break condition cb ) _clearbp ;; # clear all brkpts. g ) return ;; # start/resume execution s ) let _steps=${args:-1} return ;; # single-step N times(default 1) x ) _xtrace ;; # toggle execution trace pr ) _print $args ;; # print lines in file \? | h | help ) _menu ;; # print command menu hi ) history ;; # show command history q ) _cleanup; exit ;; # quit \! ) eval $args ;; # run shell command * ) _msg "Invalid command: $cmd" ; _menu ;; esac done } # see if next line no. is a brkpt. _at_linenumbp() { if [ -z "${_linebp}" ]; then return 1 fi echo "${_curline}" | egrep "(${_linebp%\|})" >/dev/null 2>&1 return $? } # search string brkpts to see if next line in script matches. _at_stringbp() { local l; if [ -z "$_stringbp" ]; then return 1; fi l=${_lines[$_curline-$_firstline+1]} echo "${l}" | egrep "*(${_stringbp%\|})*" >/dev/null 2>&1 return $? } # print message to stderr _msg() { echo -e "$@" >&2 } # set brkpt(s) at given line numbers and/or strings # by appending lines to brkpt file _setbp() { declare -i n case "$1" in "") _listbp ;; [0-9]*) #number, set brkpt at that line n=$1 _linebp="${_linebp}$n|" _msg "Breakpoint at line " $1 ;; *) #string, set brkpt at next line w/string _stringbp="${_stringbp}$@|" _msg "Breakpoint at next line containing $@." ;; esac } # list brkpts and break condition. _listbp() { _msg "Breakpoints at lines:" _msg "${_linebp//\|/ }" _msg "Breakpoints at strings:" _msg "${_stringbp//\|/ }" _msg "Break on condition:" _msg "$_brcond" } # set or clear break condition _setbc() { if [ -n "$@" ] ; then _brcond=$args _msg "Break when true: $_brcond" else _brcond= _msg "Break condition cleared" fi } # clear all brkpts _clearbp() { _linebp= _stringbp= _msg "All breakpoints cleared" } # toggle execution trace feature _xtrace() { let _trace="! $_trace" _msg "Execution trace \c" let " $_trace" && _msg "on." || _msg "off." } # print command menu _menu() { # made commands to be debugger commands by default, no need for '*' prefix _msg 'bashdb commands: bp N set breakpoint at line N bp string set breakpoint at next line containing "string" bp list breakpoints and break condition bc string set break condition to "string" bc clear break condition cb clear all breakpoints g start/resume execution s [N] execute N statements (default 1) x toggle execution trace on/off (default on) pr [start|.] [cnt] print "cnt" lines from line no. "start" ?, h, help print this menu hi show command history q quit ! cmd [args] execute command "cmd" with "args" default: last command (in "[ ]" at the prompt) Readline command line editing (emacs/vi mode) is available' } # erase temp files before exiting _cleanup() { rm $_dbgfile 2>/dev/null } # read $_BUFSIZ lines from $_guineapig into _lines array, starting from line $1 # save number of first line read in _firstline _readin() { declare -i _i=1 let _firstline=$1 SEDCMD="$_firstline,$(($_firstline+$_BUFSIZ))p" sed -n "$SEDCMD" $_guineapig > /tmp/_script.$$ while read -r _lines[$_i]; do _i=_i+1 done < /tmp/_script.$$ rm -f /tmp/_script.$$ 2>/dev/null } _print() { typeset _start _cnt if [ -z "$1" ] || [ "$1" = . ]; then _start=$_curline else _start=$1 fi _cnt=${2:-9} SEDCMD="$_start,$(($_start+$_cnt))p" pr -tn $_guineapig | sed -n "$SEDCMD" } --- NEW FILE: PERMISSION --- >From mi...@or... Tue Aug 1 12:13:20 1995 Flags: 10 Return-Path: mi...@or... Received: from ruby.ora.com (ruby.ora.com [198.112.208.25]) by odin.INS.CWRU.Edu with ESMTP (8.6.12+cwru/CWRU-2.1-ins) id MAA01565; Tue, 1 Aug 1995 12:13:18 -0400 (from mi...@or... for <ch...@od...>) Received: (from fax@localhost) by ruby.ora.com (8.6.12/8.6.11) with UUCP id MAA23251; Tue, 1 Aug 1995 12:07:51 -0400 Received: by los.ora.com (4.1/Spike-2.1) id AA00672; Tue, 1 Aug 95 08:57:32 EDT Date: Tue, 1 Aug 95 08:57:32 EDT From: mi...@or... (Michael Loukides) Message-Id: <950...@lo...> Subject: Re: Ksh debugger from Rosenblatt's book [for bash] To: Chet Ramey <ch...@od...> Cc: cm...@or..., ca...@ii..., bro...@tm... In-Reply-To: Chet Ramey <ch...@od...>, Mon, 31 Jul 1995 16:22:48 -0400 I've modified a (modified) version of Bill Rosenblatt's ksh debugger to work with bash-2.0. Does ORA have any problem with me distributing it with bash-2.0? That's great! Go ahead and circulate it; in fact, we should probably grab it and stick it in our ftp archive, and put a reference to it in the book. (Too late to actually discuss the thing, at least for this edition). ------- --- NEW FILE: bashdb.pre --- # bashdb.pre - Bourne-Again Shell Debugger preamble file # prepended to script being ddebugged #arguments: # $1 = name of original guineapig script # $2 = dir where temp files are stored # $3 = dir where bashdb.pre and bashdb.fns are stored # separate history file for bashdb HISTFILE=~/.bashdb_history set -o history set +H # prompt for trace line PS4="${1}" _dbgfile=$0 _guineapig=$1 _tmpdir=$2 _libdir=$3 shift 3 #move user's args into place . $_libdir/bashdb.fns #read in the debugger functions _linebp= _stringbp= let _trace=1 #init execution trace flag to on #read guineapig file into _lines array _readin 1 trap _cleanup EXIT #erase files before exiting let _steps=1 #no. of statements to run after setting trap #set LINENO, gets incremented to 1 LINENO=0 trap '_steptrap $LINENO' DEBUG : |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:35
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/examples/complete In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/examples/complete Added Files: complete-examples complete.freebsd complete.gnu-longopt complete.ianmac complete2.ianmac Log Message: Pristine source --- NEW FILE: complete.freebsd --- #Date: Wed, 31 Jan 2001 12:53:56 -0800 #From: Aaron Smith <aa...@mu...> #To: fre...@fr... #Subject: useful bash completion function for pkg commands #Message-ID: <200...@ge...> #hi all. i just wanted to share this bash completion function i wrote that #completes package names for pkg_info and pkg_delete. i find this a great #help when dealing with port management. programmed completion requires #bash-2.04. _pkg_func () { local cur cur=${COMP_WORDS[COMP_CWORD]} if [[ $cur == '-' ]]; then if [[ ${COMP_WORDS[0]} == 'pkg_info' ]]; then COMPREPLY=(-a -c -d -D -i -k -r -R -p -L -q -I -m -v -e -l) return 0; elif [[ ${COMP_WORDS[0]} == 'pkg_delete' ]]; then COMPREPLY=(-v -D -d -n -f -p) return 0; fi fi COMPREPLY=( $(compgen -d /var/db/pkg/$cur | sed sN/var/db/pkg/NNg) ) return 0 } complete -F _pkg_func pkg_delete pkg_info --- NEW FILE: complete.ianmac --- ##### #To: ch...@po..., sar...@lu... #Message-Id: <slr...@lo...> #Posted-To: comp.unix.shell, gnu.bash.bug #Subject: bash 2.04 programmable completion examples #Reply-To: ia...@li..., ia...@ca... #Summary: examples of programmable completion for bash 2.04 #Date: Thu, 13 Jul 2000 00:52:33 -0400 (EDT) #From: ia...@li... (Ian Macdonald) ##### ######################################################################### # Turn on extended globbing shopt -s extglob # A lot of the following one-liners were taken directly from the # completion examples provided with the bash 2.04 source distribution # Make directory commands see only directories complete -d cd mkdir rmdir pushd # Make file commands see only files complete -f cat less more chown ln strip complete -f -X '*.gz' gzip complete -f -X '*.Z' compress complete -f -X '!*.+(Z|gz|tgz|Gz)' gunzip zcat zmore complete -f -X '!*.Z' uncompress zmore zcat complete -f -X '!*.+(gif|jpg|jpeg|GIF|JPG|bmp)' ee xv complete -f -X '!*.+(ps|PS|ps.gz)' gv complete -f -X '!*.+(dvi|DVI)' dvips xdvi dviselect dvitype complete -f -X '!*.+(pdf|PDF)' acroread xpdf complete -f -X '!*.texi*' makeinfo texi2dvi texi2html complete -f -X '!*.+(tex|TEX)' tex latex slitex complete -f -X '!*.+(mp3|MP3)' mpg123 # kill sees only signals complete -A signal kill -P '%' # user commands see only users complete -u finger su usermod userdel passwd # bg completes with stopped jobs complete -A stopped -P '%' bg # other job commands complete -j -P '%' fg jobs disown # network commands complete with hostname complete -A hostname ssh rsh telnet rlogin ftp ping fping host traceroute \ nslookup # export and others complete with shell variables complete -v export local readonly unset # set completes with set options complete -A setopt set # shopt completes with shopt options complete -A shopt shopt # helptopics complete -A helptopic help # unalias completes with aliases complete -a unalias # various commands complete with commands complete -c command type nohup exec nice eval strace gdb # bind completes with readline bindings (make this more intelligent) complete -A binding bind # Now we get to the meat of the file, the functions themselves. Some # of these are works in progress. Most assume GNU versions of the # tools in question and may require modifications for use on vanilla # UNIX systems. # # A couple of functions may have non-portable, Linux specific code in # them, but this will be noted where applicable # GNU chown(1) completion. This should be expanded to allow the use of # ':' as well as '.' as the user.group separator. # _chown () { local cur prev user group COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} # do not attempt completion if we're specifying an option if [ "${cur:0:1}" = "-" ]; then return 0; fi # first parameter on line or first since an option? if [ $COMP_CWORD -eq 1 ] || [ "${prev:0:1}" = "-" ]; then case "$cur" in [a-zA-Z]*.*) user=${cur%.*} group=${cur#*.} COMPREPLY=( $( awk 'BEGIN {FS=":"} \ {if ($1 ~ /^'$group'/) print $1}' \ /etc/group ) ) for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do COMPREPLY[i]=$user.${COMPREPLY[i]} done return 0 ;; *) COMPREPLY=( $( compgen -u $cur -S '.' ) ) return 0 ;; esac else COMPREPLY=( $( compgen -f $cur ) ) fi return 0 } complete -F _chown chown # umount(8) completion. This relies on the mount point being the third # space-delimited field in the output of mount(8) # _umount () { local cur COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} # could rewrite the cut | grep to be a sed command, but this is # clearer and doesn't result in much overhead COMPREPLY=( $( mount | cut -d' ' -f 3 | grep ^$cur) ) return 0 } complete -F _umount umount # GID completion. This will get a list of all valid group names from # /etc/group and should work anywhere. # _gid_func () { local cur COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} COMPREPLY=( $( awk 'BEGIN {FS=":"} {if ($1 ~ /^'$cur'/) print $1}' \ /etc/group ) ) return 0 } complete -F _gid_func groupdel groupmod # mount(8) completion. This will pull a list of possible mounts out of # /etc/fstab, unless the word being completed contains a ':', which # would indicate the specification of an NFS server. In that case, we # query the server for a list of all available exports and complete on # that instead. # _mount () { local cur COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} case "$cur" in *:*) COMPREPLY=( $( /usr/sbin/showmount -e --no-headers ${cur%%:*} |\ grep ^${cur#*:} | awk '{print $1}')) return 0 ;; *) COMPREPLY=( $( awk '{if ($2 ~ /\//) print $2}' /etc/fstab | \ grep ^$cur )) return 0 ;; esac } complete -F _mount mount # Linux rmmod(1) completion. This completes on a list of all currently # installed kernel modules. # _rmmod () { local cur COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} COMPREPLY=($( lsmod | awk '{if (NR != 1 && $1 ~ /^'$cur'/) print $1}')) return 0 } complete -F _rmmod rmmod # Linux insmod(1) completion. This completes on a list of all # available modules for the version of the kernel currently running. # _insmod () { local cur modpath COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} modpath=/lib/modules/`uname -r` COMPREPLY=($( ls -R $modpath | sed -ne 's/^\('$cur'.*\)\.o$/\1/p')) return 0 } complete -F _insmod insmod depmod modprobe # man(1) completion. This relies on the security enhanced version of # GNU locate(1). UNIX variants having non-numeric man page sections # other than l, m and n should add the appropriate sections to the # first clause of the case statement. # # This is Linux specific, in that 'man <section> <page>' is the # expected syntax. This allows one to do something like # 'man 3 str<tab>' to obtain a list of all string handling syscalls on # the system. # _man () { local cur prev COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} case "$prev" in [0-9lmn]) COMPREPLY=($( slocate -ql 0 -r '/man/man'$prev'/'$cur | \ sed -ne 's/^.*\/\('$cur'[^.\/]*\)\..*$/\1/p' )) return 0 ;; *) COMPREPLY=($( slocate -ql 0 -r '/man/man./'$cur | \ sed -ne 's/^.*\/\('$cur'[^.\/]*\)\..*$/\1/p' )) return 0 ;; esac } complete -F _man man # Linux killall(1) completion. This wouldn't be much use on, say, # Solaris, where killall does exactly that: kills ALL processes. # # This could be improved. For example, it currently doesn't take # command line options into account # _killall () { local cur prev COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} case "$prev" in -[A-Z0-9]*) # get a list of processes (the first sed evaluation # takes care of swapped out processes, the second # takes care of getting the basename of the process) COMPREPLY=( $( ps ahx | awk '{if ($5 ~ /^'$cur'/) print $5}' | \ sed -e 's#[]\[]##g' -e 's#^.*/##' )) return 0 ;; esac # first parameter can be either a signal or a process if [ $COMP_CWORD -eq 1 ]; then # standard signal completion is rather braindead, so we need # to hack around to get what we want here, which is to # complete on a dash, followed by the signal name minus # the SIG prefix COMPREPLY=( $( compgen -A signal SIG${cur#-} )) for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do COMPREPLY[i]=-${COMPREPLY[i]#SIG} done fi # get processes, adding to signals if applicable COMPREPLY=( ${COMPREPLY[*]} $( ps ahx | \ awk '{if ($5 ~ /^'$cur'/) print $5}' | \ sed -e 's#[]\[]##g' -e 's#^.*/##' )) return 0 } complete -F _killall killall # GNU find(1) completion. This makes heavy use of ksh style extended # globs and contains Linux specific code for completing the parameter # to the -fstype option. # _find () { local cur prev COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]#-} prev=${COMP_WORDS[COMP_CWORD-1]} case "$prev" in -@(max|min)depth) COMPREPLY=( $( compgen -W '0 1 2 3 4 5 6 7 8 9' ) ) return 0 ;; -?(a)newer|-fls|-fprint?(0|f)) COMPREPLY=( $( compgen -f $cur ) ) return 0 ;; -fstype) # this is highly non-portable (the option to -d is a tab) COMPREPLY=( $( cut -d' ' -f 2 /proc/filesystems | grep ^$cur ) ) return 0 ;; -gid) COMPREPLY=( $( awk 'BEGIN {FS=":"} \ {if ($3 ~ /^'$cur'/) print $3}' /etc/group ) ) return 0 ;; -group) COMPREPLY=( $( awk 'BEGIN {FS=":"} \ {if ($1 ~ /^'$cur'/) print $1}' /etc/group ) ) return 0 ;; -?(x)type) COMPREPLY=( $( compgen -W 'b c d p f l s' $cur ) ) return 0 ;; -uid) COMPREPLY=( $( awk 'BEGIN {FS=":"} \ {if ($3 ~ /^'$cur'/) print $3}' /etc/passwd ) ) return 0 ;; -user) COMPREPLY=( $( compgen -u $cur ) ) return 0 ;; -[acm]min|-[acm]time|-?(i)?(l)name|-inum|-?(i)path|-?(i)regex| \ -links|-perm|-size|-used|-exec|-ok|-printf) # do nothing, just wait for a parameter to be given return 0 ;; esac # complete using basic options ($cur has had its dash removed here, # as otherwise compgen will bomb out with an error, since it thinks # the dash is an option to itself) COMPREPLY=( $( compgen -W 'daystart depth follow help maxdepth \ mindepth mount noleaf version xdev amin anewer atime \ cmin cnewer ctime empty false fstype gid group ilname \ iname inum ipath iregex links lname mmin mtime name \ newer nouser nogroup perm regex size true type uid \ used user xtype exec fls fprint fprint0 fprintf ok \ print print0 printf prune ls' $cur ) ) # this removes any options from the list of completions that have # already been specified somewhere on the command line. COMPREPLY=( $( echo "${COMP_WORDS[@]}-" | \ (while read -d '-' i; do [ "$i" == "" ] && continue # flatten array with spaces on either side, # otherwise we cannot grep on word boundaries of # first and last word COMPREPLY=" ${COMPREPLY[@]} " # remove word from list of completions COMPREPLY=( ${COMPREPLY/ ${i%% *} / } ) done echo ${COMPREPLY[@]}) ) ) # put dashes back for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do COMPREPLY[i]=-${COMPREPLY[i]} done return 0 } complete -F _find find # Linux ifconfig(8) completion # _ifconfig () { local cur COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} case "${COMP_WORDS[1]}" in -|*[0-9]*) COMPREPLY=( $( compgen -W '-a up down arp promisc allmulti \ metric mtu dstaddr netmask add del \ tunnel irq io_addr mem_start media \ broadcast pointopoint hw multicast \ address txqueuelen' $cur )) COMPREPLY=( $( echo " ${COMP_WORDS[@]}" | \ (while read -d ' ' i; do [ "$i" == "" ] && continue # flatten array with spaces on either side, # otherwise we cannot grep on word # boundaries of first and last word COMPREPLY=" ${COMPREPLY[@]} " # remove word from list of completions COMPREPLY=( ${COMPREPLY/ $i / } ) done echo ${COMPREPLY[@]}) ) ) return 0 ;; esac COMPREPLY=( $( ifconfig -a | sed -ne 's/^\('$cur'[^ ]*\).*$/\1/p' )) } complete -F _ifconfig ifconfig # Linux ipsec(8) completion (for FreeS/WAN). Very basic. # _ipsec () { local cur COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} COMPREPLY=( $( compgen -W 'auto barf eroute klipsdebug look manual \ pluto ranbits rsasigkey setup showdefaults \ showhostkey spi spigrp tncfg whack' $cur )) } complete -F _ipsec ipsec ######################################################################### --- NEW FILE: complete2.ianmac --- ##### #From: ia...@li... (Ian Macdonald) #Newsgroups: comp.unix.shell #Subject: More bash 2.04 completions #Date: 12 Aug 2000 09:53:40 GMT #Organization: Linuxcare, Inc. #Lines: 274 #Message-ID: <slr...@lo...> #Reply-To: ia...@li... ##### # Turn on extended globbing shopt -s extglob # cvs(1) completion # _cvs () { local cur prev COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} if [ $COMP_CWORD -eq 1 ] || [ "${prev:0:1}" = "-" ]; then COMPREPLY=( $( compgen -W 'add admin checkout commit diff \ export history import log rdiff release remove rtag status \ tag update' $cur )) else COMPREPLY=( $( compgen -f $cur )) fi return 0 } complete -F _cvs cvs # rpm(8) completion. This isn't exhaustive yet, but still provides # quite a lot of functionality. # _rpm() { dashify() { local i for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do if [ ${#COMPREPLY[i]} -le 2 ]; then COMPREPLY[i]=-${COMPREPLY[i]} else COMPREPLY[i]=--${COMPREPLY[i]} fi done } local cur cur_nodash prev COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} cur_nodash=${cur#-} prev=${COMP_WORDS[COMP_CWORD-1]} if [ $COMP_CWORD = 1 ]; then # first parameter on line case "$cur" in -b*) COMPREPLY=( $( compgen -W 'ba bb bc bi bl bp bs' \ $cur_nodash ) ) dashify return 0 ;; -t*) COMPREPLY=( $( compgen -W 'ta tb tc ti tl tp ts' \ $cur_nodash ) ) dashify return 0 ;; --*) COMPREPLY=( $( compgen -W 'help version initdb \ checksig recompile rebuild resign addsign rebuilddb \ showrc setperms setgids' ${cur_nodash#-} ) ) dashify; return 0 ;; *) COMPREPLY=( $( compgen -W 'b e F i q t U V' \ $cur_nodash ) ) dashify return 0 ;; esac fi case "${COMP_WORDS[1]}" in -[iFU]*) # complete on list of relevant options COMPREPLY=( $( compgen -W 'percent force test replacepkgs \ replacefiles root excludedocs includedocs noscripts rcfile \ ignorearch dbpath prefix ignoreos nodeps allfiles ftpproxy \ ftpport justdb httpproxy httpport noorder relocate badreloc \ notriggers excludepath ignoresize oldpackage' ${cur_nodash#-} )) dashify; # return if $cur is an option [ "${cur:0:1}" = "-" ] && return 0 # add a list of RPMS to possible completions COMPREPLY=( ${COMPREPLY[@]} $( compgen -G $cur\*.rpm ) ) return 0 ;; -qp*) # complete on list of relevant options COMPREPLY=( $( compgen -W 'scripts root rcfile whatprovides \ whatrequires requires triggeredby ftpport ftpproxy httpproxy \ httpport provides triggers dump changelog dbpath filesbypkg' \ ${cur_nodash#-} ) ) dashify; # return if $cur is an option [ "${cur:0:1}" = "-" ] && return 0 # add a list of RPMS to possible completions COMPREPLY=( ${COMPREPLY[@]} $( compgen -G $cur\*.rpm ) ) return 0 ;; -*f) # standard filename completion COMPREPLY=( $( compgen -f $cur ) ) return 0 ;; -e) # complete on list of relevant options COMPREPLY=( $( compgen -W 'allmatches noscripts notriggers \ nodeps test' ${cur_nodash#-} ) ) dashify; # return if $cur is an option [ "${cur:0:1}" = "-" ] && return 0 # complete on basename of installed RPMs COMPREPLY=( $( rpm -qa | \ sed -ne 's/^\('$cur'.*\)-[0-9a-zA-Z._]\+-[0-9.]\+$/\1/p' ) ) return 0 ;; -qa*) # complete on list of relevant options COMPREPLY=( $( compgen -W 'scripts root rcfile whatprovides \ whatrequires requires triggeredby ftpport ftpproxy httpproxy \ httpport provides triggers dump changelog dbpath specfile \ querybynumber last filesbypkg' ${cur_nodash#-} ) ) dashify; return 0 ;; -q*) # complete on list of relevant options COMPREPLY=( $( compgen -W 'scripts root rcfile whatprovides \ whatrequires requires triggeredby ftpport ftpproxy httpproxy \ httpport provides triggers dump changelog dbpath specfile \ querybynumber last filesbypkg' ${cur_nodash#-} ) ) dashify; # return if $cur is an option [ "${cur:0:1}" = "-" ] && return 0 # add a list of RPMS to possible completions COMPREPLY=( ${COMPREPLY[@]} $( rpm -qa | \ sed -ne 's/^\('$cur'.*\)-[0-9a-zA-Z._]\+-[0-9.]\+$/\1/p' ) ) return 0 ;; -[Vy]*) # complete on list of relevant options COMPREPLY=( $( compgen -W 'root rcfile dbpath nodeps nofiles \ noscripts nomd5 nopgp' ${cur_nodash#-} ) ) dashify; # return if $cur is an option [ "${cur:0:1}" = "-" ] && return 0 # add a list of RPMS to possible completions COMPREPLY=( ${COMPREPLY[@]} $( rpm -qa | \ sed -ne 's/^\('$cur'.*\)-[0-9a-zA-Z._]\+-[0-9.]\+$/\1/p' ) ) return 0 ;; -b*) # complete on list of relevant options COMPREPLY=( $( compgen -W 'short-circuit timecheck clean \ rmsource test sign buildroot target buildarch buildos' \ ${cur_nodash#-} ) ) dashify; # return if $cur is an option [ "${cur:0:1}" = "-" ] && return 0 # complete on .spec files COMPREPLY=( $( compgen -G $cur\*.spec ) ) return 0 ;; -t*) # complete on list of relevant options COMPREPLY=( $( compgen -W 'short-circuit timecheck clean \ rmsource test sign buildroot target buildarch buildos' \ ${cur_nodash#-} ) ) dashify; # return if $cur is an option [ "${cur:0:1}" = "-" ] && return 0 # complete on .tar.gz files COMPREPLY=( $( compgen -G $cur\*.tar.gz ) ) return 0 ;; --re@(build|compile)) # complete on source RPMs COMPREPLY=( $( compgen -G $cur\*.src.rpm ) ) return 0 ;; --@(checksig|@(re|add)sign)) # complete on RPMs COMPREPLY=( $( compgen -G $cur\*.rpm ) ) return 0 ;; --set@(perms|gids)) # complete on installed RPMs COMPREPLY=( ${COMPREPLY[@]} $( rpm -qa | \ sed -ne 's/^\('$cur'.*\)-[0-9a-zA-Z._]\+-[0-9.]\+$/\1/p' ) ) return 0 ;; esac } complete -F _rpm rpm # chsh(1) completion # _chsh() { local cur prev COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} if [ "$prev" = "-s" ]; then COMPREPLY=( $( chsh -l | grep ^$cur ) ) else COMPREPLY=( $( compgen -u $cur ) ) fi } complete -F _chsh chsh # chkconfig(8) completion # _chkconfig() { local cur prev COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} cur_nodash=${cur#--} prev=${COMP_WORDS[COMP_CWORD-1]} if [ $COMP_CWORD -eq 1 ]; then COMPREPLY=( $( compgen -W 'list add del level' $cur_nodash ) ) for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do COMPREPLY[i]=--${COMPREPLY[i]} done return 0 fi if [ $COMP_CWORD -eq 4 ]; then COMPREPLY=( $( compgen -W 'on off reset' $cur ) ) return 0 fi case "$prev" in @([1-6]|--@(list|add|del))) COMPREPLY=( $( compgen -W "`(cd /etc/rc.d/init.d; echo *)`" \ $cur) ) return 0 ;; --level) COMPREPLY=( $( compgen -W '1 2 3 4 5 6' $cur ) ) return 0 ;; esac } complete -F _chkconfig chkconfig ### --- NEW FILE: complete.gnu-longopt --- # # Originally from: # #Message-ID: <3B1...@wa...> #Date: Tue, 29 May 2001 20:37:25 +0200 #From: Manu Rouat <emm...@wa...> #Subject: [bash] Universal command options completion? # # #In the recent versions of bash (after 2.04) programmable #completion is available. A useful completion function #is , for a particular command, to enumerate all flags #that can be used in the command. Now, most GNU unix #commands have so-called 'long options' for example: # #ls --color=always --no-group --size # #and these are all listed when you issue a '--help' flag. #So the idea is to use that, then parse the output of the #'--help' and reinject this to compgen. The basis of the #following 'universal' completion funtion was the _configure_func' #written by Ian McDonnald (or is it Chet Ramey ?) #A dedicated function will always be better, but this is quite #convenient. I chose to use 'long options' because they are #easy to parse and explicit too (it's the point I guess...) #Lots of room for improvement ! _longopt_func () { case "$2" in -*) ;; *) return ;; esac case "$1" in \~*) eval cmd=$1 ;; *) cmd="$1" ;; esac COMPREPLY=( $("$cmd" --help | sed -e '/--/!d' -e 's/.*--\([^ ]*\).*/--\1/'| \ grep ^"$2" |sort -u) ) } complete -o default -F _longopt_func ldd wget bash id info # some examples that work --- NEW FILE: complete-examples --- # # Completion examples # # # This encapsulates the default bash completion code # call with the word to be completed as $1 # # Since programmable completion does not use the bash default completions # or the readline default of filename completion when the compspec does # not generate any matches, this may be used as a `last resort' in a # completion function to mimic the default bash completion behavior. # _bash_def_completion () { local h t COMPREPLY=() # command substitution if [[ "$1" == \$\(* ]]; then t=${1#??} COMPREPLY=( $(compgen -c -P '$(' $t) ) fi # variables with a leading `${' if [ ${#COMPREPLY[@]} -eq 0 ] && [[ "$1" == \$\{* ]]; then t=${1#??} COMPREPLY=( $(compgen -v -P '${' -S '}' $t) ) fi # variables with a leading `$' if [ ${#COMPREPLY[@]} -eq 0 ] && [[ "$1" == \$* ]]; then t=${1#?} COMPREPLY=( $(compgen -v -P '$' $t ) ) fi # username expansion if [ ${#COMPREPLY[@]} -eq 0 ] && [[ "$1" == ~* ]] && [[ "$1" != */* ]]; then t=${1#?} COMPREPLY=( $( compgen -u -P '~' $t ) ) fi # hostname if [ ${#COMPREPLY[@]} -eq 0 ] && [[ "$1" == *@* ]]; then h=${1%%@*} t=${1#*@} COMPREPLY=( $( compgen -A hostname -P "${h}@" $t ) ) fi # glob pattern if [ ${#COMPREPLY[@]} -eq 0 ]; then # sh-style glob pattern if [[ $1 == *[*?[]* ]]; then COMPREPLY=( $( compgen -G "$1" ) ) # ksh-style extended glob pattern - must be complete elif shopt -q extglob && [[ $1 == *[?*+\!@]\(*\)* ]]; then COMPREPLY=( $( compgen -G "$1" ) ) fi fi # final default is filename completion if [ ${#COMPREPLY[@]} -eq 0 ]; then COMPREPLY=( $(compgen -f "$1" ) ) fi } # # Return 1 if $1 appears to contain a redirection operator. Handles backslash # quoting (barely). # _redir_op() { case "$1" in *\\'[\<\>]'*) return 1;; *[\<\>]*) return 0;; *) return 1;; esac } # _redir_test tests the current word ($1) and the previous word ($2) for # redirection operators and does filename completion on the current word # if either one contains a redirection operator _redir_test() { if _redir_op "$1" ; then COMPREPLY=( $( compgen -f "$1" ) ) return 0 elif _redir_op "$2" ; then COMPREPLY=( $( compgen -f "$1" ) ) return 0 fi return 1 } # optional, but without this you can't use extended glob patterns shopt -s extglob # # Easy ones for the shell builtins # # nothing for: alias, break, continue, dirs, echo, eval, exit, getopts, # let, logout, popd, printf, pwd, return, shift, suspend, test, times, # umask # complete -f -- . source complete -A enabled builtin complete -d cd # this isn't exactly right yet -- needs to skip shell functions and # do $PATH lookup (or do compgen -c and filter out matches that also # appear in compgen -A function) complete -c command # could add -S '=', but that currently screws up because readline appends # a space unconditionally complete -v export local readonly complete -A helptopic help # currently same as builtins complete -d pushd complete -A shopt shopt complete -c type complete -a unalias complete -v unset # # Job control builtins: fg, bg, disown, kill, wait # kill not done yet # complete -A stopped -P '%' bg complete -j -P '%' fg jobs disown # this is not quite right at this point _wait_func () { local cur cur=${COMP_WORDS[COMP_CWORD]} case "$cur" in %*) COMPREPLY=( $(compgen -A running -P '%' ${cur#?} ) ) ;; [0-9]*) COMPREPLY=( $(jobs -p | grep ^${cur}) ) ;; *) COMPREPLY=( $(compgen -A running -P '%') $(jobs -p) ) ;; esac } complete -F _wait_func wait # # more complicated things, several as yet unimplemented # #complete -F _bind_func bind _declare_func() { local cur prev nflag opts cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} COMPREPLY=() if (( $COMP_CWORD <= 1 )) || [[ $cur == '-' ]]; then COMPREPLY=(-a -f -F -i -p -r -t -x) return 0; fi if [[ $cur == '+' ]]; then COMPREPLY=(+i +t +x) return 0; fi if [[ $prev == '-p' ]]; then COMPREPLY=( $(compgen -v $cur) ) return 0; fi return 1 } complete -F _declare_func declare typeset _enable_func() { local cur prev nflag opts cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} COMPREPLY=() if (( $COMP_CWORD <= 1 )) || [[ $cur == '-' ]]; then COMPREPLY=(-a -d -f -n -p -s) return 0; fi if [[ $prev == '-f' ]]; then COMPREPLY=( $( compgen -f $cur ) ) return 0; fi for opts in "${COMP_WORDS[@]}" ; do if [[ $opts == -*n* ]]; then nflag=1; fi done if [ -z "$nflag" ] ; then COMPREPLY=( $( compgen -A enabled $cur ) ) else COMPREPLY=( $( compgen -A disabled $cur ) ) fi return 0; } complete -F _enable_func enable _exec_func() { local cur prev cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} if (( $COMP_CWORD <= 1 )) || [[ $cur == '-' ]]; then COMPREPLY=(-a -c -l) return 0; fi if [[ $prev != -*a* ]]; then COMPREPLY=( $( compgen -c $cur ) ) return 0 fi return 1; } complete -F _exec_func exec _fc_func() { local cur prev cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} if (( $COMP_CWORD <= 1 )) || [[ $cur == '-' ]]; then COMPREPLY=(-e -n -l -r -s) return 0; fi if [[ $prev == -*e ]]; then COMPREPLY=( $(compgen -c $cur) ) return 0 fi return 1 } complete -F _fc_func fc _hash_func() { local cur prev cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} if (( $COMP_CWORD <= 1 )) || [[ $cur == '-' ]]; then COMPREPLY=(-p -r -t) return 0; fi if [[ $prev == '-p' ]]; then COMPREPLY=( $( compgen -f $cur ) ) return 0; fi COMPREPLY=( $( compgen -c $cur ) ) return 0 } complete -F _hash_func hash _history_func() { local cur prev cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} COMPREPLY=() if (( $COMP_CWORD <= 1 )) || [[ $cur == '-' ]]; then COMPREPLY=(-a -c -d -n -r -w -p -s) return 0; fi if [[ $prev == -[anrw] ]]; then COMPREPLY=( $( compgen -f $cur ) ) fi return 0 } complete -F _history_func history #complete -F _read_func read _set_func () { local cur prev cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} COMPREPLY=() _redir_test "$cur" "$prev" && return 0; if (( $COMP_CWORD <= 1 )) || [[ $cur == '-' ]]; then COMPREPLY=(-a -b -e -f -k -m -n -o -p -t -u -v -x -B -C -H -P --) return 0; fi if [[ $cur == '+' ]]; then COMPREPLY=(+a +b +e +f +k +m +n +o +p +t +u +v +x +B +C +H +P) return 0; fi if [[ $prev == [+-]o ]]; then COMPREPLY=( $(compgen -A setopt $cur) ) return 0; fi return 1; } complete -F _set_func set _trap_func () { local cur cur=${COMP_WORDS[COMP_CWORD]} if (( $COMP_CWORD <= 1 )) || [[ $cur == '-' ]]; then COMPREPLY=(-l -p) return 0; fi COMPREPLY=( $( compgen -A signal ${cur}) ) return 0 } complete -F _trap_func trap # # meta-completion (completion for complete/compgen) # _complete_meta_func() { local cur prev cmd COMPREPLY=() cmd=$1 cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} _redir_test "$cur" "$prev" && return 0; if (( $COMP_CWORD <= 1 )) || [[ "$cur" == '-' ]]; then case "$cmd" in complete) COMPREPLY=(-a -b -c -d -e -f -j -k -s -v -u -r -p -A -G -W -P -S -X -F -C);; compgen) COMPREPLY=(-a -b -c -d -e -f -j -k -s -v -u -A -G -W -P -S -X -F -C);; esac return 0 fi if [[ $prev == -A ]]; then COMPREPLY=(alias arrayvar binding builtin command directory \ disabled enabled export file 'function' helptopic hostname job keyword \ running service setopt shopt signal stopped variable) return 0 elif [[ $prev == -F ]]; then COMPREPLY=( $( compgen -A function $cur ) ) elif [[ $prev == -C ]]; then COMPREPLY=( $( compgen -c $cur ) ) else COMPREPLY=( $( compgen -c $cur ) ) fi return 0 } complete -F _complete_meta_func complete compgen # # some completions for shell reserved words # #complete -c -k time do if then else elif '{' # # external commands # complete -e printenv complete -c nohup exec nice eval trace truss strace sotruss gdb _make_targets () { local mdef makef gcmd cur prev i COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} # if prev argument is -f, return possible filename completions. # we could be a little smarter here and return matches against # `makefile Makefile *.mk', whatever exists case "$prev" in -*f) COMPREPLY=( $(compgen -f $cur ) ); return 0;; esac # if we want an option, return the possible posix options case "$cur" in -) COMPREPLY=(-e -f -i -k -n -p -q -r -S -s -t); return 0;; esac # make reads `makefile' before `Makefile' # GNU make reads `GNUmakefile' before all other makefiles, but we # check that we're completing `gmake' before checking for it if [ -f GNUmakefile ] && [ ${COMP_WORDS[0]} == gmake ]; then mdef=GNUmakefile elif [ -f makefile ]; then mdef=makefile elif [ -f Makefile ]; then mdef=Makefile else mdef=*.mk # local convention fi # before we scan for targets, see if a makefile name was specified # with -f for (( i=0; i < ${#COMP_WORDS[@]}; i++ )); do if [[ ${COMP_WORDS[i]} == -*f ]]; then eval makef=${COMP_WORDS[i+1]} # eval for tilde expansion break fi done [ -z "$makef" ] && makef=$mdef # if we have a partial word to complete, restrict completions to # matches of that word if [ -n "$2" ]; then gcmd='grep "^$2"' ; else gcmd=cat ; fi # if we don't want to use *.mk, we can take out the cat and use # test -f $makef and input redirection COMPREPLY=( $(cat $makef 2>/dev/null | awk 'BEGIN {FS=":"} /^[^.# ][^=]*:/ {print $1}' | tr -s ' ' '\012' | sort -u | eval $gcmd ) ) } complete -F _make_targets -X '+($*|*.[cho])' make gmake pmake _umount_func () { COMPREPLY=( $(mount | awk '{print $1}') ) } complete -F _umount_func umount _configure_func () { case "$2" in -*) ;; *) return ;; esac case "$1" in \~*) eval cmd=$1 ;; *) cmd="$1" ;; esac COMPREPLY=( $("$cmd" --help | awk '{if ($1 ~ /--.*/) print $1}' | grep ^"$2" | sort -u) ) } complete -F _configure_func configure complete -W '"${GROUPS[@]}"' newgrp complete -f chown ln more cat complete -d mkdir rmdir complete -f strip complete -f -X '*.gz' gzip complete -f -X '*.bz2' bzip2 complete -f -X '*.Z' compress complete -f -X '!*.+(gz|tgz|Gz)' gunzip gzcat zcat zmore complete -f -X '!*.Z' uncompress zmore zcat complete -f -X '!*.bz2' bunzip2 bzcat complete -f -X '!*.zip' unzip complete -f -X '!*.+(gif|jpg|jpeg|GIF|JPG|JPEG|bmp)' xv complete -f -X '!*.pl' perl perl5 complete -A hostname rsh telnet rlogin ftp ping xping host traceroute nslookup complete -A hostname rxterm rxterm3 rxvt2 complete -u su complete -g newgrp groupdel groupmod complete -f -X '!*.+(ps|PS)' gs gv ghostview psselect pswrap complete -f -X '!*.+(dvi|DVI)' dvips xdvi dviselect dvitype catdvi complete -f -X '!*.+(pdf|PDF)' acroread4 complete -f -X '!*.texi*' makeinfo texi2dvi texi2html complete -f -X '!*.+(tex|TEX)' tex latex slitex complete -f -X '!*.+(mp3|MP3)' mpg123 complete -f -X '!*.+(htm|html)' links w3m lynx # # other possibilities, left as exercises # #complete -F _find_func find #complete -F _man_func man #complete -F _stty_func stty |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:34
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/readline/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/readline/doc Added Files: Makefile hist.texinfo hstech.texinfo hsuser.texinfo manvers.texinfo rlman.texinfo rltech.texinfo rluser.texinfo rluserman.texinfo Log Message: Pristine source --- NEW FILE: rltech.texinfo --- @comment %**start of header (This is for running Texinfo on a region.) @setfilename rltech.info @comment %**end of header (This is for running Texinfo on a region.) @setchapternewpage odd @ifinfo This document describes the GNU Readline Library, a utility for aiding in the consitency of user interface across discrete programs that need to provide a command line interface. Copyright (C) 1988-2002 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice pare preserved on all copies. @ignore Permission is granted to process this file through TeX and print the results, provided the printed document carries copying permission [...2126 lines suppressed...] "%s: Too dangerous for me to distribute.\n" caller); fprintf (stderr, "Write it yourself.\n"); @} /* Return non-zero if ARG is a valid argument for CALLER, else print an error message and return zero. */ int valid_argument (caller, arg) char *caller, *arg; @{ if (!arg || !*arg) @{ fprintf (stderr, "%s: Argument required.\n", caller); return (0); @} return (1); @} @end smallexample --- NEW FILE: Makefile --- # Derived by hand from the generated readline-src/doc/Makefile # This makefile for Readline library documentation is in -*- text -*- mode. # Emacs likes it that way. # Copyright (C) 1996-2002 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. topdir = . srcdir = . VPATH = . prefix = /usr/local infodir = ${prefix}/info mandir = ${prefix}/man manpfx = man man1ext = 1 man1dir = $(mandir)/$(manpfx)$(man1ext) man3ext = 3 man3dir = $(mandir)/$(manpfx)$(man3ext) SHELL = /bin/sh RM = rm -f INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 BUILD_DIR = . TEXINPUTDIR = $(srcdir) MAKEINFO = LANGUAGE= makeinfo TEXI2DVI = $(srcdir)/texi2dvi TEXI2HTML = $(srcdir)/texi2html QUIETPS = #set this to -q to shut up dvips PSDPI = 300 # I don't have any 600-dpi printers DVIPS = dvips -D ${PSDPI} $(QUIETPS) -o $@ # tricky RLSRC = $(srcdir)/rlman.texinfo $(srcdir)/rluser.texinfo \ $(srcdir)/rltech.texinfo $(srcdir)/manvers.texinfo \ $(srcdir)/rluserman.texinfo HISTSRC = $(srcdir)/hist.texinfo $(srcdir)/hsuser.texinfo \ $(srcdir)/hstech.texinfo $(srcdir)/manvers.texinfo # This should be a program that converts troff to an ascii-readable format NROFF = groff -Tascii # This should be a program that converts troff to postscript GROFF = groff DVIOBJ = readline.dvi history.dvi rluserman.dvi INFOOBJ = readline.info history.info rluserman.info PSOBJ = readline.ps history.ps rluserman.ps HTMLOBJ = readline.html history.html rluserman.html INTERMEDIATE_OBJ = rlman.dvi hist.dvi rluserman.dvi CREATED_DOCS = $(DVIOBJ) $(INFOOBJ) $(PSOBJ) $(HTMLOBJ) .SUFFIXES: .ps .txt .dvi all: info dvi html ps nodvi: info html readline.dvi: $(RLSRC) TEXINPUTS=.:$(TEXINPUTDIR):$$TEXINPUTS $(TEXI2DVI) $(srcdir)/rlman.texinfo mv rlman.dvi readline.dvi readline.info: $(RLSRC) $(MAKEINFO) --no-split -I $(TEXINPUTDIR) -o $@ $(srcdir)/rlman.texinfo rluserman.dvi: $(RLSRC) TEXINPUTS=.:$(TEXINPUTDIR):$$TEXINPUTS $(TEXI2DVI) $(srcdir)/rluserman.texinfo rluserman.info: $(RLSRC) $(MAKEINFO) --no-split -I $(TEXINPUTDIR) -o $@ $(srcdir)/rluserman.texinfo history.dvi: ${HISTSRC} TEXINPUTS=.:$(TEXINPUTDIR):$$TEXINPUTS $(TEXI2DVI) $(srcdir)/hist.texinfo mv hist.dvi history.dvi history.info: ${HISTSRC} $(MAKEINFO) --no-split -I $(TEXINPUTDIR) -o $@ $(srcdir)/hist.texinfo readline.ps: readline.dvi $(RM) $@ $(DVIPS) readline.dvi rluserman.ps: rluserman.dvi $(RM) $@ $(DVIPS) rluserman.dvi history.ps: history.dvi $(RM) $@ $(DVIPS) history.dvi readline.html: ${RLSRC} $(TEXI2HTML) -menu -monolithic -I $(TEXINPUTDIR) $(srcdir)/rlman.texinfo sed -e 's:rlman.html:readline.html:' rlman.html > readline.html $(RM) rlman.html rluserman.html: ${RLSRC} $(TEXI2HTML) -menu -monolithic -I $(TEXINPUTDIR) $(srcdir)/rluserman.texinfo history.html: ${HISTSRC} $(TEXI2HTML) -menu -monolithic -I $(TEXINPUTDIR) $(srcdir)/hist.texinfo sed -e 's:hist.html:history.html:' hist.html > history.html $(RM) hist.html info: $(INFOOBJ) dvi: $(DVIOBJ) ps: $(PSOBJ) html: $(HTMLOBJ) clean: $(RM) *.aux *.cp *.fn *.ky *.log *.pg *.toc *.tp *.vr *.cps *.pgs \ *.fns *.kys *.tps *.vrs *.o core distclean: clean $(RM) $(CREATED_DOCS) $(RM) $(INTERMEDIATE_OBJ) $(RM) Makefile mostlyclean: clean maintainer-clean: clean $(RM) $(CREATED_DOCS) $(RM) $(INTERMEDIATE_OBJ) $(RM) Makefile install: @echo "This documentation should not be installed." uninstall: --- NEW FILE: manvers.texinfo --- @ignore Copyright (C) 1988-2002 Free Software Foundation, Inc. @end ignore @set EDITION 4.3 @set VERSION 4.3 @set UPDATED 2002 March 4 @set UPDATE-MONTH March 2002 @set LASTCHANGE Mon Mar 4 12:00:16 EST 2002 --- NEW FILE: hsuser.texinfo --- @ignore This file documents the user interface to the GNU History library. Copyright (C) 1988-2002 Free Software Foundation, Inc. Authored by Brian Fox and Chet Ramey. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to process this file through Tex and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the GNU Copyright statement is available to the distributee, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions. @end ignore @node Using History Interactively @chapter Using History Interactively @ifclear BashFeatures @defcodeindex bt @end ifclear @ifset BashFeatures This chapter describes how to use the @sc{gnu} History Library interactively, from a user's standpoint. It should be considered a user's guide. For information on using the @sc{gnu} History Library in other programs, see the @sc{gnu} Readline Library Manual. @end ifset @ifclear BashFeatures This chapter describes how to use the @sc{gnu} History Library interactively, from a user's standpoint. It should be considered a user's guide. For information on using the @sc{gnu} History Library in your own programs, @pxref{Programming with GNU History}. @end ifclear @ifset BashFeatures @menu * Bash History Facilities:: How Bash lets you manipulate your command history. * Bash History Builtins:: The Bash builtin commands that manipulate the command history. * History Interaction:: What it feels like using History as a user. @end menu @end ifset @ifclear BashFeatures @menu * History Interaction:: What it feels like using History as a user. @end menu @end ifclear @ifset BashFeatures @node Bash History Facilities @section Bash History Facilities @cindex command history @cindex history list When the @option{-o history} option to the @code{set} builtin is enabled (@pxref{The Set Builtin}), the shell provides access to the @dfn{command history}, the list of commands previously typed. The value of the @env{HISTSIZE} shell variable is used as the number of commands to save in a history list. The text of the last @env{$HISTSIZE} commands (default 500) is saved. The shell stores each command in the history list prior to parameter and variable expansion but after history expansion is performed, subject to the values of the shell variables @env{HISTIGNORE} and @env{HISTCONTROL}. When the shell starts up, the history is initialized from the file named by the @env{HISTFILE} variable (default @file{~/.bash_history}). The file named by the value of @env{HISTFILE} is truncated, if necessary, to contain no more than the number of lines specified by the value of the @env{HISTFILESIZE} variable. When an interactive shell exits, the last @env{$HISTSIZE} lines are copied from the history list to the file named by @env{$HISTFILE}. If the @code{histappend} shell option is set (@pxref{Bash Builtins}), the lines are appended to the history file, otherwise the history file is overwritten. If @env{HISTFILE} is unset, or if the history file is unwritable, the history is not saved. After saving the history, the history file is truncated to contain no more than @env{$HISTFILESIZE} lines. If @env{HISTFILESIZE} is not set, no truncation is performed. The builtin command @code{fc} may be used to list or edit and re-execute a portion of the history list. The @code{history} builtin may be used to display or modify the history list and manipulate the history file. When using command-line editing, search commands are available in each editing mode that provide access to the history list (@pxref{Commands For History}). The shell allows control over which commands are saved on the history list. The @env{HISTCONTROL} and @env{HISTIGNORE} variables may be set to cause the shell to save only a subset of the commands entered. The @code{cmdhist} shell option, if enabled, causes the shell to attempt to save each line of a multi-line command in the same history entry, adding semicolons where necessary to preserve syntactic correctness. The @code{lithist} shell option causes the shell to save the command with embedded newlines instead of semicolons. The @code{shopt} builtin is used to set these options. @xref{Bash Builtins}, for a description of @code{shopt}. @node Bash History Builtins @section Bash History Builtins @cindex history builtins Bash provides two builtin commands which manipulate the history list and history file. @table @code @item fc @btindex fc @example @code{fc [-e @var{ename}] [-nlr] [@var{first}] [@var{last}]} @code{fc -s [@var{pat}=@var{rep}] [@var{command}]} @end example Fix Command. In the first form, a range of commands from @var{first} to @var{last} is selected from the history list. Both @var{first} and @var{last} may be specified as a string (to locate the most recent command beginning with that string) or as a number (an index into the history list, where a negative number is used as an offset from the current command number). If @var{last} is not specified it is set to @var{first}. If @var{first} is not specified it is set to the previous command for editing and @minus{}16 for listing. If the @option{-l} flag is given, the commands are listed on standard output. The @option{-n} flag suppresses the command numbers when listing. The @option{-r} flag reverses the order of the listing. Otherwise, the editor given by @var{ename} is invoked on a file containing those commands. If @var{ename} is not given, the value of the following variable expansion is used: @code{$@{FCEDIT:-$@{EDITOR:-vi@}@}}. This says to use the value of the @env{FCEDIT} variable if set, or the value of the @env{EDITOR} variable if that is set, or @code{vi} if neither is set. When editing is complete, the edited commands are echoed and executed. In the second form, @var{command} is re-executed after each instance of @var{pat} in the selected command is replaced by @var{rep}. A useful alias to use with the @code{fc} command is @code{r='fc -s'}, so that typing @samp{r cc} runs the last command beginning with @code{cc} and typing @samp{r} re-executes the last command (@pxref{Aliases}). @item history @btindex history @example history [@var{n}] history -c history -d @var{offset} history [-anrw] [@var{filename}] history -ps @var{arg} @end example With no options, display the history list with line numbers. Lines prefixed with a @samp{*} have been modified. An argument of @var{n} lists only the last @var{n} lines. Options, if supplied, have the following meanings: @table @code @item -c Clear the history list. This may be combined with the other options to replace the history list completely. @item -d @var{offset} Delete the history entry at position @var{offset}. @var{offset} should be specified as it appears when the history is displayed. @item -a Append the new history lines (history lines entered since the beginning of the current Bash session) to the history file. @item -n Append the history lines not already read from the history file to the current history list. These are lines appended to the history file since the beginning of the current Bash session. @item -r Read the current history file and append its contents to the history list. @item -w Write out the current history to the history file. @item -p Perform history substitution on the @var{arg}s and display the result on the standard output, without storing the results in the history list. @item -s The @var{arg}s are added to the end of the history list as a single entry. @end table When any of the @option{-w}, @option{-r}, @option{-a}, or @option{-n} options is used, if @var{filename} is given, then it is used as the history file. If not, then the value of the @env{HISTFILE} variable is used. @end table @end ifset @node History Interaction @section History Expansion @cindex history expansion The History library provides a history expansion feature that is similar to the history expansion provided by @code{csh}. This section describes the syntax used to manipulate the history information. History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the current input line, or fix errors in previous commands quickly. History expansion takes place in two parts. The first is to determine which line from the history list should be used during substitution. The second is to select portions of that line for inclusion into the current one. The line selected from the history is called the @dfn{event}, and the portions of that line that are acted upon are called @dfn{words}. Various @dfn{modifiers} are available to manipulate the selected words. The line is broken into words in the same fashion that Bash does, so that several words surrounded by quotes are considered one word. History expansions are introduced by the appearance of the history expansion character, which is @samp{!} by default. @ifset BashFeatures Only @samp{\} and @samp{'} may be used to escape the history expansion character. @end ifset @ifset BashFeatures Several shell options settable with the @code{shopt} builtin (@pxref{Bash Builtins}) may be used to tailor the behavior of history expansion. If the @code{histverify} shell option is enabled, and Readline is being used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the Readline editing buffer for further modification. If Readline is being used, and the @code{histreedit} shell option is enabled, a failed history expansion will be reloaded into the Readline editing buffer for correction. The @option{-p} option to the @code{history} builtin command may be used to see what a history expansion will do before using it. The @option{-s} option to the @code{history} builtin may be used to add commands to the end of the history list without actually executing them, so that they are available for subsequent recall. This is most useful in conjunction with Readline. The shell allows control of the various characters used by the history expansion mechanism with the @code{histchars} variable. @end ifset @menu * Event Designators:: How to specify which history line to use. * Word Designators:: Specifying which words are of interest. * Modifiers:: Modifying the results of substitution. @end menu @node Event Designators @subsection Event Designators @cindex event designators An event designator is a reference to a command line entry in the history list. @cindex history events @table @asis @item @code{!} Start a history substitution, except when followed by a space, tab, the end of the line, @samp{=} or @samp{(}. @item @code{!@var{n}} Refer to command line @var{n}. @item @code{!-@var{n}} Refer to the command @var{n} lines back. @item @code{!!} Refer to the previous command. This is a synonym for @samp{!-1}. @item @code{!@var{string}} Refer to the most recent command starting with @var{string}. @item @code{!?@var{string}[?]} Refer to the most recent command containing @var{string}. The trailing @samp{?} may be omitted if the @var{string} is followed immediately by a newline. @item @code{^@var{string1}^@var{string2}^} Quick Substitution. Repeat the last command, replacing @var{string1} with @var{string2}. Equivalent to @code{!!:s/@var{string1}/@var{string2}/}. @item @code{!#} The entire command line typed so far. @end table @node Word Designators @subsection Word Designators Word designators are used to select desired words from the event. A @samp{:} separates the event specification from the word designator. It may be omitted if the word designator begins with a @samp{^}, @samp{$}, @samp{*}, @samp{-}, or @samp{%}. Words are numbered from the beginning of the line, with the first word being denoted by 0 (zero). Words are inserted into the current line separated by single spaces. @need 0.75 For example, @table @code @item !! designates the preceding command. When you type this, the preceding command is repeated in toto. @item !!:$ designates the last argument of the preceding command. This may be shortened to @code{!$}. @item !fi:2 designates the second argument of the most recent command starting with the letters @code{fi}. @end table @need 0.75 Here are the word designators: @table @code @item 0 (zero) The @code{0}th word. For many applications, this is the command word. @item @var{n} The @var{n}th word. @item ^ The first argument; that is, word 1. @item $ The last argument. @item % The word matched by the most recent @samp{?@var{string}?} search. @item @var{x}-@var{y} A range of words; @samp{-@var{y}} abbreviates @samp{0-@var{y}}. @item * All of the words, except the @code{0}th. This is a synonym for @samp{1-$}. It is not an error to use @samp{*} if there is just one word in the event; the empty string is returned in that case. @item @var{x}* Abbreviates @samp{@var{x}-$} @item @var{x}- Abbreviates @samp{@var{x}-$} like @samp{@var{x}*}, but omits the last word. @end table If a word designator is supplied without an event specification, the previous command is used as the event. @node Modifiers @subsection Modifiers After the optional word designator, you can add a sequence of one or more of the following modifiers, each preceded by a @samp{:}. @table @code @item h Remove a trailing pathname component, leaving only the head. @item t Remove all leading pathname components, leaving the tail. @item r Remove a trailing suffix of the form @samp{.@var{suffix}}, leaving the basename. @item e Remove all but the trailing suffix. @item p Print the new command but do not execute it. @ifset BashFeatures @item q Quote the substituted words, escaping further substitutions. @item x Quote the substituted words as with @samp{q}, but break into words at spaces, tabs, and newlines. @end ifset @item s/@var{old}/@var{new}/ Substitute @var{new} for the first occurrence of @var{old} in the event line. Any delimiter may be used in place of @samp{/}. The delimiter may be quoted in @var{old} and @var{new} with a single backslash. If @samp{&} appears in @var{new}, it is replaced by @var{old}. A single backslash will quote the @samp{&}. The final delimiter is optional if it is the last character on the input line. @item & Repeat the previous substitution. @item g Cause changes to be applied over the entire event line. Used in conjunction with @samp{s}, as in @code{gs/@var{old}/@var{new}/}, or with @samp{&}. @end table --- NEW FILE: hist.texinfo --- \input texinfo @c -*-texinfo-*- @c %**start of header (This is for running Texinfo on a region.) @setfilename history.info @settitle GNU History Library @c %**end of header (This is for running Texinfo on a region.) @setchapternewpage odd @include manvers.texinfo @ifinfo @dircategory Libraries @direntry * History: (history). The GNU history library API @end direntry This document describes the GNU History library, a programming tool that provides a consistent user interface for recalling lines of previously typed input. Copyright (C) 1988-2002 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice pare preserved on all copies. @ignore Permission is granted to process this file through TeX and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). @end ignore Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. @end ifinfo @titlepage @title GNU History Library @subtitle Edition @value{EDITION}, for @code{History Library} Version @value{VERSION}. @subtitle @value{UPDATE-MONTH} @author Brian Fox, Free Software Foundation @author Chet Ramey, Case Western Reserve University @page This document describes the GNU History library, a programming tool that provides a consistent user interface for recalling lines of previously typed input. Published by the Free Software Foundation @* 59 Temple Place, Suite 330, @* Boston, MA 02111 USA Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. @vskip 0pt plus 1filll Copyright @copyright{} 1988-2002 Free Software Foundation, Inc. @end titlepage @ifinfo @node Top @top GNU History Library This document describes the GNU History library, a programming tool that provides a consistent user interface for recalling lines of previously typed input. @menu * Using History Interactively:: GNU History User's Manual. * Programming with GNU History:: GNU History Programmer's Manual. * Concept Index:: Index of concepts described in this manual. * Function and Variable Index:: Index of externally visible functions and variables. @end menu @end ifinfo @syncodeindex fn vr @include hsuser.texinfo @include hstech.texinfo @node Concept Index @appendix Concept Index @printindex cp @node Function and Variable Index @appendix Function and Variable Index @printindex vr @contents @bye --- NEW FILE: hstech.texinfo --- @ignore This file documents the user interface to the GNU History library. Copyright (C) 1988-2002 Free Software Foundation, Inc. Authored by Brian Fox and Chet Ramey. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to process this file through Tex and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the GNU Copyright statement is available to the distributee, and provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions. @end ignore @node Programming with GNU History @chapter Programming with GNU History This chapter describes how to interface programs that you write with the @sc{gnu} History Library. It should be considered a technical guide. For information on the interactive use of @sc{gnu} History, @pxref{Using History Interactively}. @menu * Introduction to History:: What is the GNU History library for? * History Storage:: How information is stored. * History Functions:: Functions that you can use. * History Variables:: Variables that control behaviour. * History Programming Example:: Example of using the GNU History Library. @end menu @node Introduction to History @section Introduction to History Many programs read input from the user a line at a time. The @sc{gnu} History library is able to keep track of those lines, associate arbitrary data with each line, and utilize information from previous lines in composing new ones. The programmer using the History library has available functions for remembering lines on a history list, associating arbitrary data with a line, removing lines from the list, searching through the list for a line containing an arbitrary text string, and referencing any line in the list directly. In addition, a history @dfn{expansion} function is available which provides for a consistent user interface across different programs. The user using programs written with the History library has the benefit of a consistent user interface with a set of well-known commands for manipulating the text of previous lines and using that text in new commands. The basic history manipulation commands are similar to the history substitution provided by @code{csh}. If the programmer desires, he can use the Readline library, which includes some history manipulation by default, and has the added advantage of command line editing. Before declaring any functions using any functionality the History library provides in other code, an application writer should include the file @code{<readline/history.h>} in any file that uses the History library's features. It supplies extern declarations for all of the library's public functions and variables, and declares all of the public data structures. @node History Storage @section History Storage The history list is an array of history entries. A history entry is declared as follows: @example typedef void *histdata_t; typedef struct _hist_entry @{ char *line; histdata_t data; @} HIST_ENTRY; @end example The history list itself might therefore be declared as @example HIST_ENTRY **the_history_list; @end example The state of the History library is encapsulated into a single structure: @example /* * A structure used to pass around the current state of the history. */ typedef struct _hist_state @{ HIST_ENTRY **entries; /* Pointer to the entries themselves. */ int offset; /* The location pointer within this array. */ int length; /* Number of elements within this array. */ int size; /* Number of slots allocated to this array. */ int flags; @} HISTORY_STATE; @end example If the flags member includes @code{HS_STIFLED}, the history has been stifled. @node History Functions @section History Functions This section describes the calling sequence for the various functions exported by the @sc{gnu} History library. @menu * Initializing History and State Management:: Functions to call when you want to use history in a program. * History List Management:: Functions used to manage the list of history entries. * Information About the History List:: Functions returning information about the history list. * Moving Around the History List:: Functions used to change the position in the history list. * Searching the History List:: Functions to search the history list for entries containing a string. * Managing the History File:: Functions that read and write a file containing the history list. * History Expansion:: Functions to perform csh-like history expansion. @end menu @node Initializing History and State Management @subsection Initializing History and State Management This section describes functions used to initialize and manage the state of the History library when you want to use the history functions in your program. @deftypefun void using_history (void) Begin a session in which the history functions might be used. This initializes the interactive variables. @end deftypefun @deftypefun {HISTORY_STATE *} history_get_history_state (void) Return a structure describing the current state of the input history. @end deftypefun @deftypefun void history_set_history_state (HISTORY_STATE *state) Set the state of the history list according to @var{state}. @end deftypefun @node History List Management @subsection History List Management These functions manage individual entries on the history list, or set parameters managing the list itself. @deftypefun void add_history (const char *string) Place @var{string} at the end of the history list. The associated data field (if any) is set to @code{NULL}. @end deftypefun @deftypefun {HIST_ENTRY *} remove_history (int which) Remove history entry at offset @var{which} from the history. The removed element is returned so you can free the line, data, and containing structure. @end deftypefun @deftypefun {HIST_ENTRY *} replace_history_entry (int which, const char *line, histdata_t data) Make the history entry at offset @var{which} have @var{line} and @var{data}. This returns the old entry so you can dispose of the data. In the case of an invalid @var{which}, a @code{NULL} pointer is returned. @end deftypefun @deftypefun void clear_history (void) Clear the history list by deleting all the entries. @end deftypefun @deftypefun void stifle_history (int max) Stifle the history list, remembering only the last @var{max} entries. @end deftypefun @deftypefun int unstifle_history (void) Stop stifling the history. This returns the previously-set maximum number of history entries (as set by @code{stifle_history()}). The value is positive if the history was stifled, negative if it wasn't. @end deftypefun @deftypefun int history_is_stifled (void) Returns non-zero if the history is stifled, zero if it is not. @end deftypefun @node Information About the History List @subsection Information About the History List These functions return information about the entire history list or individual list entries. @deftypefun {HIST_ENTRY **} history_list (void) Return a @code{NULL} terminated array of @code{HIST_ENTRY *} which is the current input history. Element 0 of this list is the beginning of time. If there is no history, return @code{NULL}. @end deftypefun @deftypefun int where_history (void) Returns the offset of the current history element. @end deftypefun @deftypefun {HIST_ENTRY *} current_history (void) Return the history entry at the current position, as determined by @code{where_history()}. If there is no entry there, return a @code{NULL} pointer. @end deftypefun @deftypefun {HIST_ENTRY *} history_get (int offset) Return the history entry at position @var{offset}, starting from @code{history_base} (@pxref{History Variables}). If there is no entry there, or if @var{offset} is greater than the history length, return a @code{NULL} pointer. @end deftypefun @deftypefun int history_total_bytes (void) Return the number of bytes that the primary history entries are using. This function returns the sum of the lengths of all the lines in the history. @end deftypefun @node Moving Around the History List @subsection Moving Around the History List These functions allow the current index into the history list to be set or changed. @deftypefun int history_set_pos (int pos) Set the current history offset to @var{pos}, an absolute index into the list. Returns 1 on success, 0 if @var{pos} is less than zero or greater than the number of history entries. @end deftypefun @deftypefun {HIST_ENTRY *} previous_history (void) Back up the current history offset to the previous history entry, and return a pointer to that entry. If there is no previous entry, return a @code{NULL} pointer. @end deftypefun @deftypefun {HIST_ENTRY *} next_history (void) Move the current history offset forward to the next history entry, and return the a pointer to that entry. If there is no next entry, return a @code{NULL} pointer. @end deftypefun @node Searching the History List @subsection Searching the History List @cindex History Searching These functions allow searching of the history list for entries containing a specific string. Searching may be performed both forward and backward from the current history position. The search may be @dfn{anchored}, meaning that the string must match at the beginning of the history entry. @cindex anchored search @deftypefun int history_search (const char *string, int direction) Search the history for @var{string}, starting at the current history offset. If @var{direction} is less than 0, then the search is through previous entries, otherwise through subsequent entries. If @var{string} is found, then the current history index is set to that history entry, and the value returned is the offset in the line of the entry where @var{string} was found. Otherwise, nothing is changed, and a -1 is returned. @end deftypefun @deftypefun int history_search_prefix (const char *string, int direction) Search the history for @var{string}, starting at the current history offset. The search is anchored: matching lines must begin with @var{string}. If @var{direction} is less than 0, then the search is through previous entries, otherwise through subsequent entries. If @var{string} is found, then the current history index is set to that entry, and the return value is 0. Otherwise, nothing is changed, and a -1 is returned. @end deftypefun @deftypefun int history_search_pos (const char *string, int direction, int pos) Search for @var{string} in the history list, starting at @var{pos}, an absolute index into the list. If @var{direction} is negative, the search proceeds backward from @var{pos}, otherwise forward. Returns the absolute index of the history element where @var{string} was found, or -1 otherwise. @end deftypefun @node Managing the History File @subsection Managing the History File The History library can read the history from and write it to a file. This section documents the functions for managing a history file. @deftypefun int read_history (const char *filename) Add the contents of @var{filename} to the history list, a line at a time. If @var{filename} is @code{NULL}, then read from @file{~/.history}. Returns 0 if successful, or @code{errno} if not. @end deftypefun @deftypefun int read_history_range (const char *filename, int from, int to) Read a range of lines from @var{filename}, adding them to the history list. Start reading at line @var{from} and end at @var{to}. If @var{from} is zero, start at the beginning. If @var{to} is less than @var{from}, then read until the end of the file. If @var{filename} is @code{NULL}, then read from @file{~/.history}. Returns 0 if successful, or @code{errno} if not. @end deftypefun @deftypefun int write_history (const char *filename) Write the current history to @var{filename}, overwriting @var{filename} if necessary. If @var{filename} is @code{NULL}, then write the history list to @file{~/.history}. Returns 0 on success, or @code{errno} on a read or write error. @end deftypefun @deftypefun int append_history (int nelements, const char *filename) Append the last @var{nelements} of the history list to @var{filename}. If @var{filename} is @code{NULL}, then append to @file{~/.history}. Returns 0 on success, or @code{errno} on a read or write error. @end deftypefun @deftypefun int history_truncate_file (const char *filename, int nlines) Truncate the history file @var{filename}, leaving only the last @var{nlines} lines. If @var{filename} is @code{NULL}, then @file{~/.history} is truncated. Returns 0 on success, or @code{errno} on failure. @end deftypefun @node History Expansion @subsection History Expansion These functions implement history expansion. @deftypefun int history_expand (char *string, char **output) Expand @var{string}, placing the result into @var{output}, a pointer to a string (@pxref{History Interaction}). Returns: @table @code @item 0 If no expansions took place (or, if the only change in the text was the removal of escape characters preceding the history expansion character); @item 1 if expansions did take place; @item -1 if there was an error in expansion; @item 2 if the returned line should be displayed, but not executed, as with the @code{:p} modifier (@pxref{Modifiers}). @end table If an error ocurred in expansion, then @var{output} contains a descriptive error message. @end deftypefun @deftypefun {char *} get_history_event (const char *string, int *cindex, int qchar) Returns the text of the history event beginning at @var{string} + @var{*cindex}. @var{*cindex} is modified to point to after the event specifier. At function entry, @var{cindex} points to the index into @var{string} where the history event specification begins. @var{qchar} is a character that is allowed to end the event specification in addition to the ``normal'' terminating characters. @end deftypefun @deftypefun {char **} history_tokenize (const char *string) Return an array of tokens parsed out of @var{string}, much as the shell might. The tokens are split on the characters in the @var{history_word_delimiters} variable, and shell quoting conventions are obeyed. @end deftypefun @deftypefun {char *} history_arg_extract (int first, int last, const char *string) Extract a string segment consisting of the @var{first} through @var{last} arguments present in @var{string}. Arguments are split using @code{history_tokenize}. @end deftypefun @node History Variables @section History Variables This section describes the externally-visible variables exported by the @sc{gnu} History Library. @deftypevar int history_base The logical offset of the first entry in the history list. @end deftypevar @deftypevar int history_length The number of entries currently stored in the history list. @end deftypevar @deftypevar int history_max_entries The maximum number of history entries. This must be changed using @code{stifle_history()}. @end deftypevar @deftypevar char history_expansion_char The character that introduces a history event. The default is @samp{!}. Setting this to 0 inhibits history expansion. @end deftypevar @deftypevar char history_subst_char The character that invokes word substitution if found at the start of a line. The default is @samp{^}. @end deftypevar @deftypevar char history_comment_char During tokenization, if this character is seen as the first character of a word, then it and all subsequent characters up to a newline are ignored, suppressing history expansion for the remainder of the line. This is disabled by default. @end deftypevar @deftypevar {char *} history_word_delimiters The characters that separate tokens for @code{history_tokenize()}. The default value is @code{" \t\n()<>;&|"}. @end deftypevar @deftypevar {char *} history_no_expand_chars The list of characters which inhibit history expansion if found immediately following @var{history_expansion_char}. The default is space, tab, newline, carriage return, and @samp{=}. @end deftypevar @deftypevar {char *} history_search_delimiter_chars The list of additional characters which can delimit a history search string, in addition to space, TAB, @samp{:} and @samp{?} in the case of a substring search. The default is empty. @end deftypevar @deftypevar int history_quotes_inhibit_expansion If non-zero, single-quoted words are not scanned for the history expansion character. The default value is 0. @end deftypevar @deftypevar {rl_linebuf_func_t *} history_inhibit_expansion_function This should be set to the address of a function that takes two arguments: a @code{char *} (@var{string}) and an @code{int} index into that string (@var{i}). It should return a non-zero value if the history expansion starting at @var{string[i]} should not be performed; zero if the expansion should be done. It is intended for use by applications like Bash that use the history expansion character for additional purposes. By default, this variable is set to @code{NULL}. @end deftypevar @node History Programming Example @section History Programming Example The following program demonstrates simple use of the @sc{gnu} History Library. @smallexample #include <stdio.h> #include <readline/history.h> main (argc, argv) int argc; char **argv; @{ char line[1024], *t; int len, done = 0; line[0] = 0; using_history (); while (!done) @{ printf ("history$ "); fflush (stdout); t = fgets (line, sizeof (line) - 1, stdin); if (t && *t) @{ len = strlen (t); if (t[len - 1] == '\n') t[len - 1] = '\0'; @} if (!t) strcpy (line, "quit"); if (line[0]) @{ char *expansion; int result; result = history_expand (line, &expansion); if (result) fprintf (stderr, "%s\n", expansion); if (result < 0 || result == 2) @{ free (expansion); continue; @} add_history (expansion); strncpy (line, expansion, sizeof (line) - 1); free (expansion); @} if (strcmp (line, "quit") == 0) done = 1; else if (strcmp (line, "save") == 0) write_history ("history_file"); else if (strcmp (line, "read") == 0) read_history ("history_file"); else if (strcmp (line, "list") == 0) @{ register HIST_ENTRY **the_list; register int i; the_list = history_list (); if (the_list) for (i = 0; the_list[i]; i++) printf ("%d: %s\n", i + history_base, the_list[i]->line); @} else if (strncmp (line, "delete", 6) == 0) @{ int which; if ((sscanf (line + 6, "%d", &which)) == 1) @{ HIST_ENTRY *entry = remove_history (which); if (!entry) fprintf (stderr, "No such entry %d\n", which); else @{ free (entry->line); free (entry); @} @} else @{ fprintf (stderr, "non-numeric arg given to `delete'\n"); @} @} @} @} @end smallexample --- NEW FILE: rluserman.texinfo --- \input texinfo @c -*-texinfo-*- @comment %**start of header (This is for running Texinfo on a region.) @setfilename rluserman.info @settitle GNU Readline Library @comment %**end of header (This is for running Texinfo on a region.) @setchapternewpage odd @include manvers.texinfo @ifinfo @dircategory Libraries @direntry * RLuserman: (rluserman). The GNU readline library User's Manual. @end direntry This document describes the end user interface of the GNU Readline Library, a utility which aids in the consistency of user interface across discrete programs that need to provide a command line interface. Copyright (C) 1988-2002 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice pare preserved on all copies. @ignore Permission is granted to process this file through TeX and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). @end ignore Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. @end ifinfo @titlepage @title GNU Readline Library User Interface @subtitle Edition @value{EDITION}, for @code{Readline Library} Version @value{VERSION}. @subtitle @value{UPDATE-MONTH} @author Brian Fox, Free Software Foundation @author Chet Ramey, Case Western Reserve University @page This document describes the end user interface of the GNU Readline Library, a utility which aids in the consistency of user interface across discrete programs that need to provide a command line interface. Published by the Free Software Foundation @* 59 Temple Place, Suite 330, @* Boston, MA 02111 USA Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. @vskip 0pt plus 1filll Copyright @copyright{} 1988-2002 Free Software Foundation, Inc. @end titlepage @ifinfo @node Top @top GNU Readline Library This document describes the end user interface of the GNU Readline Library, a utility which aids in the consistency of user interface across discrete programs that need to provide a command line interface. @menu * Command Line Editing:: GNU Readline User's Manual. @end menu @end ifinfo @include rluser.texinfo @contents @bye --- NEW FILE: rlman.texinfo --- \input texinfo @c -*-texinfo-*- @comment %**start of header (This is for running Texinfo on a region.) @setfilename readline.info @settitle GNU Readline Library @comment %**end of header (This is for running Texinfo on a region.) @synindex vr fn @setchapternewpage odd @include manvers.texinfo @ifinfo @dircategory Libraries @direntry * Readline: (readline). The GNU readline library API @end direntry This document describes the GNU Readline Library, a utility which aids in the consistency of user interface across discrete programs that need to provide a command line interface. Copyright (C) 1988-2002 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice pare preserved on all copies. @ignore Permission is granted to process this file through TeX and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). @end ignore Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. @end ifinfo @titlepage @title GNU Readline Library @subtitle Edition @value{EDITION}, for @code{Readline Library} Version @value{VERSION}. @subtitle @value{UPDATE-MONTH} @author Brian Fox, Free Software Foundation @author Chet Ramey, Case Western Reserve University @page This document describes the GNU Readline Library, a utility which aids in the consistency of user interface across discrete programs that need to provide a command line interface. Published by the Free Software Foundation @* 59 Temple Place, Suite 330, @* Boston, MA 02111 USA Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. @vskip 0pt plus 1filll Copyright @copyright{} 1988-2002 Free Software Foundation, Inc. @end titlepage @ifinfo @node Top @top GNU Readline Library This document describes the GNU Readline Library, a utility which aids in the consistency of user interface across discrete programs that need to provide a command line interface. @menu * Command Line Editing:: GNU Readline User's Manual. * Programming with GNU Readline:: GNU Readline Programmer's Manual. * Concept Index:: Index of concepts described in this manual. * Function and Variable Index:: Index of externally visible functions and variables. @end menu @end ifinfo @include rluser.texinfo @include rltech.texinfo @node Concept Index @unnumbered Concept Index @printindex cp @node Function and Variable Index @unnumbered Function and Variable Index @printindex fn @contents @bye --- NEW FILE: rluser.texinfo --- @comment %**start of header (This is for running Texinfo on a region.) @setfilename rluser.info @comment %**end of header (This is for running Texinfo on a region.) @setchapternewpage odd @ignore This file documents the end user interface to the GNU command line editing features. It is to be an appendix to manuals for programs which use these features. There is a document entitled "readline.texinfo" which contains both end-user and programmer documentation for the GNU Readline Library. Copyright (C) 1988-2002 Free Software Foundation, Inc. Authored by Brian Fox and Chet Ramey. Permission is granted to process this file through Tex and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this [...1757 lines suppressed...] A leading @samp{!} in @var{filterpat} negates the pattern; in this case, any completion not matching @var{filterpat} is removed. @item -P @var{prefix} @var{prefix} is added at the beginning of each possible completion after all other options have been applied. @item -S @var{suffix} @var{suffix} is appended to each possible completion after all other options have been applied. @end table The return value is true unless an invalid option is supplied, an option other than @option{-p} or @option{-r} is supplied without a @var{name} argument, an attempt is made to remove a completion specification for a @var{name} for which no specification exists, or an error occurs adding a completion specification. @end table @end ifset |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:34
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/include In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/include Added Files: ansi_stdlib.h chartypes.h filecntl.h maxpath.h memalloc.h ocache.h posixdir.h posixjmp.h posixstat.h posixtime.h posixwait.h shmbutil.h shtty.h stdc.h systimes.h typemax.h unionwait.h Log Message: Pristine source --- NEW FILE: maxpath.h --- /* maxpath.h - Find out what this system thinks PATH_MAX and NAME_MAX are. */ /* Copyright (C) 1993 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_MAXPATH_H_) #define _MAXPATH_H_ /* These values are supposed to be in <limits.h> or one of the files it includes. */ #if defined (HAVE_LIMITS_H) # include <limits.h> #endif /* !HAVE_LIMITS_H */ /* If PATH_MAX is not defined, look for MAXPATHLEN */ #if !defined (PATH_MAX) # if defined (HAVE_SYS_PARAM_H) # include <sys/param.h> # define maxpath_param_h # endif # if defined (MAXPATHLEN) && !defined (PATH_MAX) # define PATH_MAX MAXPATHLEN # endif /* MAXPATHLEN && !PATH_MAX */ #endif /* !PATH_MAX */ /* If NAME_MAX is not defined, look for MAXNAMLEN */ #if !defined (NAME_MAX) # if defined (HAVE_SYS_PARAM_H) && !defined (maxpath_param_h) # include <sys/param.h> # endif # if defined (MAXNAMLEN) && !defined (NAME_MAX) # define NAME_MAX MAXNAMLEN # endif /* MAXNAMLEN && !NAME_MAX */ #endif /* !NAME_MAX */ /* Default POSIX values */ #if !defined (PATH_MAX) && defined (_POSIX_PATH_MAX) # define PATH_MAX _POSIX_PATH_MAX #endif #if !defined (NAME_MAX) && defined (_POSIX_NAME_MAX) # define NAME_MAX _POSIX_NAME_MAX #endif /* Default values */ #if !defined (PATH_MAX) # define PATH_MAX 1024 #endif #if !defined (NAME_MAX) # define NAME_MAX 14 #endif #if PATH_MAX < 1024 # undef PATH_MAX # define PATH_MAX 1024 #endif #endif /* _MAXPATH_H_ */ --- NEW FILE: unionwait.h --- /* unionwait.h -- definitions for using a `union wait' on systems without one. */ /* Copyright (C) 1996 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #ifndef _UNIONWAIT_H #define _UNIONWAIT_H #if !defined (WORDS_BIGENDIAN) union wait { int w_status; /* used in syscall */ /* Terminated process status. */ struct { unsigned short w_Termsig : 7, /* termination signal */ w_Coredump : 1, /* core dump indicator */ w_Retcode : 8, /* exit code if w_termsig==0 */ w_Fill1 : 16; /* high 16 bits unused */ } w_T; /* Stopped process status. Returned only for traced children unless requested with the WUNTRACED option bit. */ struct { unsigned short w_Stopval : 8, /* == W_STOPPED if stopped */ w_Stopsig : 8, /* actually zero on XENIX */ w_Fill2 : 16; /* high 16 bits unused */ } w_S; }; #else /* WORDS_BIGENDIAN */ /* This is for big-endian machines like the IBM RT, HP 9000, or Sun-3 */ union wait { int w_status; /* used in syscall */ /* Terminated process status. */ struct { unsigned short w_Fill1 : 16; /* high 16 bits unused */ unsigned w_Retcode : 8; /* exit code if w_termsig==0 */ unsigned w_Coredump : 1; /* core dump indicator */ unsigned w_Termsig : 7; /* termination signal */ } w_T; /* Stopped process status. Returned only for traced children unless requested with the WUNTRACED option bit. */ struct { unsigned short w_Fill2 : 16; /* high 16 bits unused */ unsigned w_Stopsig : 8; /* signal that stopped us */ unsigned w_Stopval : 8; /* == W_STOPPED if stopped */ } w_S; }; #endif /* WORDS_BIGENDIAN */ #define w_termsig w_T.w_Termsig #define w_coredump w_T.w_Coredump #define w_retcode w_T.w_Retcode #define w_stopval w_S.w_Stopval #define w_stopsig w_S.w_Stopsig #define WSTOPPED 0177 #define WIFSTOPPED(x) ((x).w_stopval == WSTOPPED) #define WIFEXITED(x) ((x).w_stopval != WSTOPPED && (x).w_termsig == 0) #define WIFSIGNALED(x) ((x).w_stopval != WSTOPPED && (x).w_termsig != 0) #define WTERMSIG(x) ((x).w_termsig) #define WSTOPSIG(x) ((x).w_stopsig) #define WEXITSTATUS(x) ((x).w_retcode) #define WIFCORED(x) ((x).w_coredump) #endif /* _UNIONWAIT_H */ --- NEW FILE: ansi_stdlib.h --- /* ansi_stdlib.h -- An ANSI Standard stdlib.h. */ /* A minimal stdlib.h containing extern declarations for those functions that bash uses. */ /* Copyright (C) 1993 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_STDLIB_H_) #define _STDLIB_H_ 1 /* String conversion functions. */ extern int atoi (); extern double atof (); extern double strtod (); /* Memory allocation functions. */ /* Generic pointer type. */ #ifndef PTR_T #if defined (__STDC__) # define PTR_T void * #else # define PTR_T char * #endif #endif /* PTR_T */ extern PTR_T malloc (); extern PTR_T realloc (); extern void free (); /* Other miscellaneous functions. */ extern void abort (); extern void exit (); extern char *getenv (); extern void qsort (); #endif /* _STDLIB_H */ --- NEW FILE: memalloc.h --- /* memalloc.h -- consolidate code for including alloca.h or malloc.h and defining alloca. */ /* Copyright (C) 1993 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_MEMALLOC_H_) # define _MEMALLOC_H_ #if defined (sparc) && defined (sun) && !defined (HAVE_ALLOCA_H) # define HAVE_ALLOCA_H #endif #if defined (__GNUC__) && !defined (HAVE_ALLOCA) # define HAVE_ALLOCA #endif #if defined (HAVE_ALLOCA_H) && !defined (HAVE_ALLOCA) && !defined (C_ALLOCA) # define HAVE_ALLOCA #endif /* HAVE_ALLOCA_H && !HAVE_ALLOCA */ #if defined (__GNUC__) && !defined (C_ALLOCA) # undef alloca # define alloca __builtin_alloca #else /* !__GNUC__ || C_ALLOCA */ # if defined (HAVE_ALLOCA_H) && !defined (C_ALLOCA) # if defined (IBMESA) # include <malloc.h> # else /* !IBMESA */ # include <alloca.h> # endif /* !IBMESA */ # else /* !HAVE_ALLOCA_H || C_ALLOCA */ # if defined (__hpux) && defined (__STDC__) && !defined (alloca) extern void *alloca (); # else # if !defined (alloca) # if defined (__STDC__) extern void *alloca (size_t); # else extern char *alloca (); # endif /* !__STDC__ */ # endif /* !alloca */ # endif /* !__hpux || !__STDC__ && !alloca */ # endif /* !HAVE_ALLOCA_H || C_ALLOCA */ #endif /* !__GNUC__ || C_ALLOCA */ #endif /* _MEMALLOC_H_ */ --- NEW FILE: posixdir.h --- /* posixdir.h -- Posix directory reading includes and defines. */ /* Copyright (C) 1987,1991 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* This file should be included instead of <dirent.h> or <sys/dir.h>. */ #if !defined (_POSIXDIR_H_) #define _POSIXDIR_H_ #if defined (HAVE_DIRENT_H) # include <dirent.h> # define D_NAMLEN(d) (strlen ((d)->d_name)) #else # if defined (HAVE_SYS_NDIR_H) # include <sys/ndir.h> # endif # if defined (HAVE_SYS_DIR_H) # include <sys/dir.h> # endif # if defined (HAVE_NDIR_H) # include <ndir.h> # endif # if !defined (dirent) # define dirent direct # endif /* !dirent */ # define D_NAMLEN(d) ((d)->d_namlen) #endif /* !HAVE_DIRENT_H */ #if defined (STRUCT_DIRENT_HAS_D_INO) && !defined (STRUCT_DIRENT_HAS_D_FILENO) # define d_fileno d_ino #endif #if defined (_POSIX_SOURCE) && (!defined (STRUCT_DIRENT_HAS_D_INO) || defined (BROKEN_DIRENT_D_INO)) /* Posix does not require that the d_ino field be present, and some systems do not provide it. */ # define REAL_DIR_ENTRY(dp) 1 #else # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0) #endif /* _POSIX_SOURCE */ #endif /* !_POSIXDIR_H_ */ --- NEW FILE: typemax.h --- /* typemax.h -- encapsulate max values for long, long long, etc. */ /* Copyright (C) 2001 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* * NOTE: This should be included after config.h, limits.h, stdint.h, and * inttypes.h */ #ifndef _SH_TYPEMAX_H #define _SH_TYPEMAX_H #ifndef CHAR_BIT # define CHAR_BIT 8 #endif /* Nonzero if the integer type T is signed. */ #ifndef TYPE_SIGNED # define TYPE_SIGNED(t) (! ((t) 0 < (t) -1)) #endif #ifndef TYPE_MINIMUM # define TYPE_MINIMUM(t) ((t) (TYPE_SIGNED (t) \ ? ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1) \ : (t) 0)) #endif #ifndef TYPE_MAXIMUM # define TYPE_MAXIMUM(t) ((t) (~ (t) 0 - TYPE_MINIMUM (t))) #endif #ifdef HAVE_LONG_LONG # ifndef LLONG_MAX # define LLONG_MAX TYPE_MAXIMUM(long long int) # define LLONG_MIN TYPE_MINIMUM(long long int) # endif # ifndef ULLONG_MAX # define ULLONG_MAX TYPE_MAXIMUM(unsigned long long int) # endif #endif #ifndef ULONG_MAX # define ULONG_MAX ((unsigned long) ~(unsigned long) 0) #endif #ifndef LONG_MAX # define LONG_MAX ((long int) (ULONG_MAX >> 1)) # define LONG_MIN ((long int) (-LONG_MAX - 1L)) #endif #ifndef INT_MAX /* ouch */ # define INT_MAX TYPE_MAXIMUM(int) # define INT_MIN TYPE_MINIMUM(int) # define UINT_MAX ((unsigned int) ~(unsigned int)0) #endif /* workaround for gcc bug in versions < 2.7 */ #if defined (HAVE_LONG_LONG) && __GNUC__ == 2 && __GNUC_MINOR__ < 7 static const unsigned long long int maxquad = ULLONG_MAX; # undef ULLONG_MAX # define ULLONG_MAX maxquad #endif #endif /* _SH_TYPEMAX_H */ --- NEW FILE: filecntl.h --- /* filecntl.h - Definitions to set file descriptors to close-on-exec. */ /* Copyright (C) 1993 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_FILECNTL_H_) #define _FILECNTL_H_ #include <fcntl.h> /* Definitions to set file descriptors to close-on-exec, the Posix way. */ #if !defined (FD_CLOEXEC) #define FD_CLOEXEC 1 #endif #define FD_NCLOEXEC 0 #define SET_CLOSE_ON_EXEC(fd) (fcntl ((fd), F_SETFD, FD_CLOEXEC)) #define SET_OPEN_ON_EXEC(fd) (fcntl ((fd), F_SETFD, FD_NCLOEXEC)) /* How to open a file in non-blocking mode, the Posix.1 way. */ #if !defined (O_NONBLOCK) # if defined (O_NDELAY) # define O_NONBLOCK O_NDELAY # else # define O_NONBLOCK 0 # endif #endif #endif /* ! _FILECNTL_H_ */ --- NEW FILE: posixtime.h --- /* posixtime.h -- wrapper for time.h, sys/times.h mess. */ /* Copyright (C) 1999 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #ifndef _POSIXTIME_H_ #define _POSIXTIME_H_ /* include this after config.h */ /* Some systems require this, mostly for the definition of `struct timezone'. For example, Dynix/ptx has that definition in <time.h> rather than sys/time.h */ #if defined (TIME_WITH_SYS_TIME) # include <sys/time.h> # include <time.h> #else # if defined (HAVE_SYS_TIME_H) # include <sys/time.h> # else # include <time.h> # endif #endif #if !defined (HAVE_SYSCONF) || !defined (_SC_CLK_TCK) # if !defined (CLK_TCK) # if defined (HZ) # define CLK_TCK HZ # else # define CLK_TCK 60 /* 60HZ */ # endif # endif /* !CLK_TCK */ #endif /* !HAVE_SYSCONF && !_SC_CLK_TCK */ #endif /* _POSIXTIME_H_ */ --- NEW FILE: chartypes.h --- /* chartypes.h -- extend ctype.h */ /* Copyright (C) 2001 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #ifndef _SH_CHARTYPES_H #define _SH_CHARTYPES_H #include <ctype.h> /* Jim Meyering writes: "... Some ctype macros are valid only for character codes that isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when using /bin/cc or gcc but without giving an ansi option). So, all ctype uses should be through macros like ISPRINT... If STDC_HEADERS is defined, then autoconf has verified that the ctype macros don't need to be guarded with references to isascii. ... Defining IN_CTYPE_DOMAIN to 1 should let any compiler worth its salt eliminate the && through constant folding." Solaris defines some of these symbols so we must undefine them first. */ #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII) # define IN_CTYPE_DOMAIN(c) 1 #else # define IN_CTYPE_DOMAIN(c) isascii(c) #endif #if !defined (isspace) && !defined (HAVE_ISSPACE) # define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f') #endif #if !defined (isprint) && !defined (HAVE_ISPRINT) # define isprint(c) (isalpha(c) || isdigit(c) || ispunct(c)) #endif #if defined (isblank) || defined (HAVE_ISBLANK) # define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c)) #else # define ISBLANK(c) ((c) == ' ' || (c) == '\t') #endif #if defined (isgraph) || defined (HAVE_ISGRAPH) # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c)) #else # define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c)) #endif #if !defined (isxdigit) && !defined (HAVE_ISXDIGIT) # define isxdigit(c) (((c) >= '0' && (c) <= '9') || ((c) >= 'a' && (c) <= 'f') || ((c) >= 'A' && (c) <= 'F')) #endif #undef ISPRINT #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c)) #define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c)) #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c)) #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c)) #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c)) #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c)) #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c)) #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c)) #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c)) #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c)) #define ISLETTER(c) (ISALPHA(c)) #define DIGIT(c) ((c) >= '0' && (c) <= '9') #define ISWORD(c) (ISLETTER(c) || DIGIT(c) || ((c) == '_')) #define HEXVALUE(c) \ (((c) >= 'a' && (c) <= 'f') \ ? (c)-'a'+10 \ : (c) >= 'A' && (c) <= 'F' ? (c)-'A'+10 : (c)-'0') #ifndef ISOCTAL # define ISOCTAL(c) ((c) >= '0' && (c) <= '7') #endif #define OCTVALUE(c) ((c) - '0') #define TODIGIT(c) ((c) - '0') #define TOCHAR(c) ((c) + '0') #define TOLOWER(c) (ISUPPER(c) ? tolower(c) : (c)) #define TOUPPER(c) (ISLOWER(c) ? toupper(c) : (c)) #ifndef TOCTRL /* letter to control char -- ASCII. The TOUPPER is in there so \ce and \cE will map to the same character in $'...' expansions. */ # define TOCTRL(x) (TOUPPER(x) & 037) #endif #ifndef UNCTRL /* control char to letter -- ASCII */ # define UNCTRL(x) (TOUPPER((x) | 0x40)) #endif #endif /* _SH_CHARTYPES_H */ --- NEW FILE: ocache.h --- /* ocache.h -- a minimal object caching implementation. */ /* Copyright (C) 2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_OCACHE_H_) #define _OCACHE_H_ 1 #ifndef PTR_T #if defined (__STDC__) # define PTR_T void * #else # define PTR_T char * #endif #endif /* PTR_T */ #define OC_MEMSET(memp, xch, nbytes) \ do { \ if ((nbytes) <= 32) { \ register char * mzp = (char *)(memp); \ unsigned long mctmp = (nbytes); \ register long mcn; \ if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp &= 7; } \ switch (mctmp) { \ case 0: for(;;) { *mzp++ = xch; \ case 7: *mzp++ = xch; \ case 6: *mzp++ = xch; \ case 5: *mzp++ = xch; \ case 4: *mzp++ = xch; \ case 3: *mzp++ = xch; \ case 2: *mzp++ = xch; \ case 1: *mzp++ = xch; if(mcn <= 0) break; mcn--; } \ } \ } else \ memset ((memp), (xch), (nbytes)); \ } while(0) typedef struct objcache { PTR_T data; int cs; /* cache size, number of objects */ int nc; /* number of cache entries */ } sh_obj_cache_t; /* Create an object cache C of N pointers to OTYPE. */ #define ocache_create(c, otype, n) \ do { \ (c).data = xmalloc((n) * sizeof (otype *)); \ (c).cs = (n); \ (c).nc = 0; \ } while (0) /* Destroy an object cache C. */ #define ocache_destroy(c) \ do { \ if ((c).data) \ xfree ((c).data); \ (c).data = 0; \ (c).cs = (c).nc = 0; \ } while (0) /* Free all cached items, which are pointers to OTYPE, in object cache C. */ #define ocache_flush(c, otype) \ do { \ while ((c).nc > 0) \ xfree (((otype **)((c).data))[--(c).nc]); \ } while (0) /* * Allocate a new item of type pointer to OTYPE, using data from object * cache C if any cached items exist, otherwise calling xmalloc. Return * the object in R. */ #define ocache_alloc(c, otype, r) \ do { \ if ((c).nc > 0) { \ (r) = (otype *)((otype **)((c).data))[--(c).nc]; \ } else \ (r) = (otype *)xmalloc (sizeof (otype)); \ } while (0) /* * Free an item R of type pointer to OTYPE, adding to object cache C if * there is room and calling xfree if the cache is full. If R is added * to the object cache, the contents are scrambled. */ #define ocache_free(c, otype, r) \ do { \ if ((c).nc < (c).cs) { \ OC_MEMSET ((r), 0xdf, sizeof(otype)); \ ((otype **)((c).data))[(c).nc++] = (r); \ } else \ xfree (r); \ } while (0) /* * One may declare and use an object cache as (for instance): * * sh_obj_cache_t wdcache = {0, 0, 0}; * sh_obj_cache_t wlcache = {0, 0, 0}; * * ocache_create(wdcache, WORD_DESC, 30); * ocache_create(wlcache, WORD_LIST, 30); * * WORD_DESC *wd; * ocache_alloc (wdcache, WORD_DESC, wd); * * WORD_LIST *wl; * ocache_alloc (wlcache, WORD_LIST, wl); * * ocache_free(wdcache, WORD_DESC, wd); * ocache_free(wlcache, WORD_LIST, wl); * * The use is almost arbitrary. */ #endif /* _OCACHE_H */ --- NEW FILE: posixstat.h --- /* posixstat.h -- Posix stat(2) definitions for systems that don't have them. */ /* Copyright (C) 1987,1991 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* This file should be included instead of <sys/stat.h>. It relies on the local sys/stat.h to work though. */ #if !defined (_POSIXSTAT_H_) #define _POSIXSTAT_H_ #include <sys/stat.h> #if defined (STAT_MACROS_BROKEN) # undef S_ISBLK # undef S_ISCHR # undef S_ISDIR # undef S_ISFIFO # undef S_ISREG # undef S_ISLNK #endif /* STAT_MACROS_BROKEN */ /* These are guaranteed to work only on isc386 */ #if !defined (S_IFDIR) && !defined (S_ISDIR) # define S_IFDIR 0040000 #endif /* !S_IFDIR && !S_ISDIR */ #if !defined (S_IFMT) # define S_IFMT 0170000 #endif /* !S_IFMT */ /* Posix 1003.1 5.6.1.1 <sys/stat.h> file types */ /* Some Posix-wannabe systems define _S_IF* macros instead of S_IF*, but do not provide the S_IS* macros that Posix requires. */ #if defined (_S_IFMT) && !defined (S_IFMT) #define S_IFMT _S_IFMT #endif #if defined (_S_IFIFO) && !defined (S_IFIFO) #define S_IFIFO _S_IFIFO #endif #if defined (_S_IFCHR) && !defined (S_IFCHR) #define S_IFCHR _S_IFCHR #endif #if defined (_S_IFDIR) && !defined (S_IFDIR) #define S_IFDIR _S_IFDIR #endif #if defined (_S_IFBLK) && !defined (S_IFBLK) #define S_IFBLK _S_IFBLK #endif #if defined (_S_IFREG) && !defined (S_IFREG) #define S_IFREG _S_IFREG #endif #if defined (_S_IFLNK) && !defined (S_IFLNK) #define S_IFLNK _S_IFLNK #endif #if defined (_S_IFSOCK) && !defined (S_IFSOCK) #define S_IFSOCK _S_IFSOCK #endif /* Test for each symbol individually and define the ones necessary (some systems claiming Posix compatibility define some but not all). */ #if defined (S_IFBLK) && !defined (S_ISBLK) #define S_ISBLK(m) (((m)&S_IFMT) == S_IFBLK) /* block device */ #endif #if defined (S_IFCHR) && !defined (S_ISCHR) #define S_ISCHR(m) (((m)&S_IFMT) == S_IFCHR) /* character device */ #endif #if defined (S_IFDIR) && !defined (S_ISDIR) #define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR) /* directory */ #endif #if defined (S_IFREG) && !defined (S_ISREG) #define S_ISREG(m) (((m)&S_IFMT) == S_IFREG) /* file */ #endif #if defined (S_IFIFO) && !defined (S_ISFIFO) #define S_ISFIFO(m) (((m)&S_IFMT) == S_IFIFO) /* fifo - named pipe */ #endif #if defined (S_IFLNK) && !defined (S_ISLNK) #define S_ISLNK(m) (((m)&S_IFMT) == S_IFLNK) /* symbolic link */ #endif #if defined (S_IFSOCK) && !defined (S_ISSOCK) #define S_ISSOCK(m) (((m)&S_IFMT) == S_IFSOCK) /* socket */ #endif /* * POSIX 1003.1 5.6.1.2 <sys/stat.h> File Modes */ #if !defined (S_IRWXU) # if !defined (S_IREAD) # define S_IREAD 00400 # define S_IWRITE 00200 # define S_IEXEC 00100 # endif /* S_IREAD */ # if !defined (S_IRUSR) # define S_IRUSR S_IREAD /* read, owner */ # define S_IWUSR S_IWRITE /* write, owner */ # define S_IXUSR S_IEXEC /* execute, owner */ # define S_IRGRP (S_IREAD >> 3) /* read, group */ # define S_IWGRP (S_IWRITE >> 3) /* write, group */ # define S_IXGRP (S_IEXEC >> 3) /* execute, group */ # define S_IROTH (S_IREAD >> 6) /* read, other */ # define S_IWOTH (S_IWRITE >> 6) /* write, other */ # define S_IXOTH (S_IEXEC >> 6) /* execute, other */ # endif /* !S_IRUSR */ # define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR) # define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP) # define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH) #endif /* !S_IRWXU */ /* These are non-standard, but are used in builtins.c$symbolic_umask() */ #define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH) #define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH) #define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH) #endif /* _POSIXSTAT_H_ */ --- NEW FILE: systimes.h --- /* Copyright (C) 1991, 1992, 1996 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* * POSIX Standard: 4.5.2 Process Times <sys/times.h> */ /* * If we don't have a standard system clock_t type, this must be included * after config.h */ #ifndef _BASH_SYSTIMES_H #define _BASH_SYSTIMES_H 1 #if defined (HAVE_SYS_TIMES_H) # include <sys/times.h> #else /* !HAVE_SYS_TIMES_H */ #include <stdc.h> /* Structure describing CPU time used by a process and its children. */ struct tms { clock_t tms_utime; /* User CPU time. */ clock_t tms_stime; /* System CPU time. */ clock_t tms_cutime; /* User CPU time of dead children. */ clock_t tms_cstime; /* System CPU time of dead children. */ }; /* Store the CPU time used by this process and all its dead descendents in BUFFER. Return the elapsed real time from an arbitrary point in the past (the bash emulation uses the epoch), or (clock_t) -1 for errors. All times are in CLK_TCKths of a second. */ extern clock_t times __P((struct tms *buffer)); #endif /* !HAVE_SYS_TIMES_H */ #endif /* _BASH_SYSTIMES_H */ --- NEW FILE: posixjmp.h --- /* posixjmp.h -- wrapper for setjmp.h with changes for POSIX systems. */ /* Copyright (C) 1987,1991 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #ifndef _POSIXJMP_H_ #define _POSIXJMP_H_ #include <setjmp.h> /* This *must* be included *after* config.h */ #if defined (HAVE_POSIX_SIGSETJMP) # define procenv_t sigjmp_buf # if !defined (__OPENNT) # undef setjmp # define setjmp(x) sigsetjmp((x), 1) # undef longjmp # define longjmp(x, n) siglongjmp((x), (n)) # endif /* !__OPENNT */ #else # define procenv_t jmp_buf #endif #endif /* _POSIXJMP_H_ */ --- NEW FILE: shtty.h --- /* Copyright (C) 1999 Free Software Foundation, Inc. */ /* This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* * shtty.h -- include the correct system-dependent files to manipulate the * tty */ #ifndef __SH_TTY_H_ #define __SH_TTY_H_ #include "stdc.h" #if defined (_POSIX_VERSION) && defined (HAVE_TERMIOS_H) && defined (HAVE_TCGETATTR) && !defined (TERMIOS_MISSING) # define TERMIOS_TTY_DRIVER #else # if defined (HAVE_TERMIO_H) # define TERMIO_TTY_DRIVER # else # define NEW_TTY_DRIVER # endif #endif /* * The _POSIX_SOURCE define is to avoid multiple symbol definitions * between sys/ioctl.h and termios.h. Ditto for the test against SunOS4 * and the undefining of several symbols. */ #ifdef TERMIOS_TTY_DRIVER # if (defined (SunOS4) || defined (SunOS5)) && !defined (_POSIX_SOURCE) # define _POSIX_SOURCE # endif # if defined (SunOS4) # undef ECHO # undef NOFLSH # undef TOSTOP # endif /* SunOS4 */ # include <termios.h> # define TTYSTRUCT struct termios #else # ifdef TERMIO_TTY_DRIVER # include <termio.h> # define TTYSTRUCT struct termio # else /* NEW_TTY_DRIVER */ # include <sgtty.h> # define TTYSTRUCT struct sgttyb # endif #endif /* Functions imported from lib/sh/shtty.c */ /* Get and set terminal attributes for the file descriptor passed as an argument. */ extern int ttgetattr __P((int, TTYSTRUCT *)); extern int ttsetattr __P((int, TTYSTRUCT *)); /* Save and restore the terminal's attributes from static storage. */ extern void ttsave __P((void)); extern void ttrestore __P((void)); /* Return the attributes corresponding to the file descriptor (0 or 1) passed as an argument. */ extern TTYSTRUCT *ttattr __P((int)); /* These functions only operate on the passed TTYSTRUCT; they don't actually change anything with the kernel's current tty settings. */ extern int tt_setonechar __P((TTYSTRUCT *)); extern int tt_setnoecho __P((TTYSTRUCT *)); extern int tt_seteightbit __P((TTYSTRUCT *)); extern int tt_setnocanon __P((TTYSTRUCT *)); extern int tt_setcbreak __P((TTYSTRUCT *)); /* These functions are all generally mutually exclusive. If you call more than one (bracketed with calls to ttsave and ttrestore, of course), the right thing will happen, but more system calls will be executed than absolutely necessary. You can do all of this yourself with the other functions; these are only conveniences. */ extern int ttonechar __P((void)); extern int ttnoecho __P((void)); extern int tteightbit __P((void)); extern int ttnocanon __P((void)); extern int ttcbreak __P((void)); #endif --- NEW FILE: shmbutil.h --- /* shmbutil.h -- utility functions for multibyte characters. */ /* Copyright (C) 2002 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_SH_MBUTIL_H_) #define _SH_MBUTIL_H_ #include "stdc.h" /************************************************/ /* check multibyte capability for I18N code */ /************************************************/ /* For platforms which support the ISO C amendement 1 functionality we support user defined character classes. */ /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */ #if defined (HAVE_WCTYPE_H) && defined (HAVE_WCHAR_H) # include <wchar.h> # include <wctype.h> # if defined (HAVE_MBSRTOWCS) /* system is supposed to support XPG5 */ # define HANDLE_MULTIBYTE 1 # endif #endif /* HAVE_WCTYPE_H && HAVE_WCHAR_H */ /* Some systems, like BeOS, have multibyte encodings but lack mbstate_t. */ #if HANDLE_MULTIBYTE && !defined (HAVE_MBSTATE_T) # define wcsrtombs(dest, src, len, ps) (wcsrtombs) (dest, src, len, 0) # define mbsrtowcs(dest, src, len, ps) (mbsrtowcs) (dest, src, len, 0) # define wcrtomb(s, wc, ps) (wcrtomb) (s, wc, 0) # define mbrtowc(pwc, s, n, ps) (mbrtowc) (pwc, s, n, 0) # define mbrlen(s, n, ps) (mbrlen) (s, n, 0) # define mbstate_t int #endif /* HANDLE_MULTIBYTE && !HAVE_MBSTATE_T */ /* Make sure MB_LEN_MAX is at least 16 on systems that claim to be able to handle multibyte chars (some systems define MB_LEN_MAX as 1) */ #ifdef HANDLE_MULTIBYTE # include <limits.h> # if defined(MB_LEN_MAX) && (MB_LEN_MAX < 16) # undef MB_LEN_MAX # endif # if !defined (MB_LEN_MAX) # define MB_LEN_MAX 16 # endif #endif /* HANDLE_MULTIBYTE */ /************************************************/ /* end of multibyte capability checks for I18N */ /************************************************/ #if defined (HANDLE_MULTIBYTE) extern size_t xmbsrtowcs __P((wchar_t *, const char **, size_t, mbstate_t *)); extern char *xstrchr __P((const char *, int)); #else /* !HANDLE_MULTIBYTE */ #undef MB_LEN_MAX #undef MB_CUR_MAX #define MB_LEN_MAX 1 #define MB_CUR_MAX 1 #undef xstrchr #define xstrchr(s, c) strchr(s, c) #endif /* !HANDLE_MULTIBYTE */ /* Declare and initialize a multibyte state. Call must be terminated with `;'. */ #if defined (HANDLE_MULTIBYTE) # define DECLARE_MBSTATE \ mbstate_t state; \ memset (&state, '\0', sizeof (mbstate_t)) #else # define DECLARE_MBSTATE #endif /* !HANDLE_MULTIBYTE */ /* Initialize or reinitialize a multibyte state named `state'. Call must be terminated with `;'. */ #if defined (HANDLE_MULTIBYTE) # define INITIALIZE_MBSTATE memset (&state, '\0', sizeof (mbstate_t)) #else # define INITIALIZE_MBSTATE #endif /* !HANDLE_MULTIBYTE */ /* Advance one (possibly multi-byte) character in string _STR of length _STRSIZE, starting at index _I. STATE must have already been declared. */ #if defined (HANDLE_MULTIBYTE) # define ADVANCE_CHAR(_str, _strsize, _i) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ \ state_bak = state; \ mblength = mbrlen ((_str) + (_i), (_strsize) - (_i), &state); \ \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ (_i)++; \ } \ else \ (_i) += mblength; \ } \ else \ (_i)++; \ } \ while (0) #else # define ADVANCE_CHAR(_str, _strsize, _i) (_i)++ #endif /* !HANDLE_MULTIBYTE */ /* Advance one (possibly multibyte) character in the string _STR of length _STRSIZE. SPECIAL: assume that _STR will be incremented by 1 after this call. */ #if defined (HANDLE_MULTIBYTE) # define ADVANCE_CHAR_P(_str, _strsize) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ \ state_bak = state; \ mblength = mbrlen ((_str), (_strsize), &state); \ \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ (_str) += (mblength < 1) ? 0 : (mblength - 1); \ } \ } \ while (0) #else # define ADVANCE_CHAR_P(_str, _strsize) #endif /* !HANDLE_MULTIBYTE */ /* Copy a single character from the string _SRC to the string _DST. _SRCEND is a pointer to the end of _SRC. */ #if defined (HANDLE_MULTIBYTE) # define COPY_CHAR_P(_dst, _src, _srcend) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _k; \ \ state_bak = state; \ mblength = mbrlen ((_src), (_srcend) - (_src), &state); \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ mblength = (mblength < 1) ? 1 : mblength; \ \ for (_k = 0; _k < mblength; _k++) \ *(_dst)++ = *(_src)++; \ } \ else \ *(_dst)++ = *(_src)++; \ } \ while (0) #else # define COPY_CHAR_P(_dst, _src, _srcend) *(_dst)++ = *(_src)++ #endif /* !HANDLE_MULTIBYTE */ /* Copy a single character from the string _SRC at index _SI to the string _DST at index _DI. _SRCEND is a pointer to the end of _SRC. */ #if defined (HANDLE_MULTIBYTE) # define COPY_CHAR_I(_dst, _di, _src, _srcend, _si) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _k; \ \ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_srcend) - ((_src)+(_si)), &state); \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ mblength = (mblength < 1) ? 1 : mblength; \ \ for (_k = 0; _k < mblength; _k++) \ _dst[_di++] = _src[_si++]; \ } \ else \ _dst[_di++] = _src[_si++]; \ } \ while (0) #else # define COPY_CHAR_I(_dst, _di, _src, _srcend, _si) _dst[_di++] = _src[_si++] #endif /* !HANDLE_MULTIBYTE */ /**************************************************************** * * * The following are only guaranteed to work in subst.c * * * ****************************************************************/ #if defined (HANDLE_MULTIBYTE) # define SCOPY_CHAR_I(_dst, _escchar, _sc, _src, _si, _slen) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _i; \ \ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_slen) - (_si), &state); \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ mblength = (mblength < 1) ? 1 : mblength; \ \ temp = xmalloc (mblength + 2); \ temp[0] = _escchar; \ for (_i = 0; _i < mblength; _i++) \ temp[_i + 1] = _src[_si++]; \ temp[mblength + 1] = '\0'; \ \ goto add_string; \ } \ else \ { \ _dst[0] = _escchar; \ _dst[1] = _sc; \ } \ } \ while (0) #else # define SCOPY_CHAR_I(_dst, _escchar, _sc, _src, _si, _slen) \ _dst[0] = _escchar; \ _dst[1] = _sc #endif /* !HANDLE_MULTIBYTE */ #if defined (HANDLE_MULTIBYTE) # define SCOPY_CHAR_M(_dst, _src, _srcend, _si) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ \ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_srcend) - ((_src) + (_si)), &state); \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ mblength = (mblength < 1) ? 1 : mblength; \ \ FASTCOPY(((_src) + (_si)), (_dst), mblength); \ \ (_dst) += mblength; \ (_si) += mblength; \ } \ else \ { \ *(_dst)++ = _src[(_si)]; \ (_si)++; \ } \ } \ while (0) #else # define SCOPY_CHAR_M(_dst, _src, _srcend, _si) \ *(_dst)++ = _src[(_si)]; \ (_si)++ #endif /* !HANDLE_MULTIBYTE */ #if HANDLE_MULTIBYTE # define SADD_MBCHAR(_dst, _src, _si, _srcsize) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ int i; \ mbstate_t state_bak; \ size_t mblength; \ \ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_srcsize) - (_si), &state); \ if (mblength == (size_t)-1 || mblength == (size_t)-2) \ { \ state = state_bak; \ mblength = 1; \ } \ if (mblength < 1) \ mblength = 1; \ \ _dst = (char *)xmalloc (mblength + 1); \ for (i = 0; i < mblength; i++) \ (_dst)[i] = (_src)[(_si)++]; \ (_dst)[mblength] = '\0'; \ \ goto add_string; \ } \ } \ while (0) #else # define SADD_MBCHAR(_dst, _src, _si, _srcsize) #endif #endif /* _SH_MBUTIL_H_ */ --- NEW FILE: stdc.h --- /* stdc.h -- macros to make source compile on both ANSI C and K&R C compilers. */ /* Copyright (C) 1993 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_STDC_H_) #define _STDC_H_ /* Adapted from BSD /usr/include/sys/cdefs.h. */ /* A function can be defined using prototypes and compile on both ANSI C and traditional C compilers with something like this: extern char *func __P((char *, char *, int)); */ #if !defined (__P) # if defined (__STDC__) || defined (__GNUC__) || defined (__cplusplus) || defined (PROTOTYPES) # define __P(protos) protos # else # define __P(protos) () # endif #endif #if defined (HAVE_STRINGIZE) # define __STRING(x) #x #else # define __STRING(x) "x" #endif #if !defined (__STDC__) #if defined (__GNUC__) /* gcc with -traditional */ # if !defined (signed) # define signed __signed # endif # if !defined (volatile) # define volatile __volatile # endif #else /* !__GNUC__ */ # if !defined (inline) # define inline # endif # if !defined (signed) # define signed # endif # if !defined (volatile) # define volatile # endif #endif /* !__GNUC__ */ #endif /* !__STDC__ */ #ifndef __attribute__ # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__ # define __attribute__(x) # endif #endif /* For those situations when gcc handles inlining a particular function but other compilers complain. */ #ifdef __GNUC__ # define INLINE inline #else # define INLINE #endif #if defined (PREFER_STDARG) # define SH_VA_START(va, arg) va_start(va, arg) #else # define SH_VA_START(va, arg) va_start(va) #endif #endif /* !_STDC_H_ */ --- NEW FILE: posixwait.h --- /* posixwait.h -- job control definitions from POSIX 1003.1 */ /* Copyright (C) 1997 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_POSIXWAIT_H_) # define _POSIXWAIT_H_ /* If _POSIX_VERSION is not defined, we assume that <sys/wait.h> defines a `union wait' and various macros used to manipulate it. Look in unionwait.h for the things we expect to find. */ #if defined (HAVE_SYS_WAIT_H) # include <sys/wait.h> #else /* !HAVE_SYS_WAIT_H */ # if !defined (_POSIX_VERSION) # include "unionwait.h" # endif #endif /* !HAVE_SYS_WAIT_H */ /* How to get the status of a job. For Posix, this is just an int, but for other systems we have to crack the union wait. */ #if !defined (_POSIX_VERSION) typedef union wait WAIT; # define WSTATUS(t) (t.w_status) #else /* _POSIX_VERSION */ typedef int WAIT; # define WSTATUS(t) (t) #endif /* _POSIX_VERSION */ /* Make sure that parameters to wait3 are defined. */ #if !defined (WNOHANG) # define WNOHANG 1 # define WUNTRACED 2 #endif /* WNOHANG */ /* More Posix P1003.1 definitions. In the POSIX versions, the parameter is passed as an `int', in the non-POSIX version, as `union wait'. */ #if defined (_POSIX_VERSION) # if !defined (WSTOPSIG) # define WSTOPSIG(s) ((s) >> 8) # endif /* !WSTOPSIG */ # if !defined (WTERMSIG) # define WTERMSIG(s) ((s) & 0177) # endif /* !WTERMSIG */ # if !defined (WEXITSTATUS) # define WEXITSTATUS(s) ((s) >> 8) # endif /* !WEXITSTATUS */ # if !defined (WIFSTOPPED) # define WIFSTOPPED(s) (((s) & 0177) == 0177) # endif /* !WIFSTOPPED */ # if !defined (WIFEXITED) # define WIFEXITED(s) (((s) & 0377) == 0) # endif /* !WIFEXITED */ # if !defined (WIFSIGNALED) # define WIFSIGNALED(s) (!WIFSTOPPED(s) && !WIFEXITED(s)) # endif /* !WIFSIGNALED */ # if !defined (WIFCORED) # define WIFCORED(s) ((s) & 0200) # endif /* !WIFCORED */ #else /* !_POSIX_VERSION */ # if !defined (WSTOPSIG) # define WSTOPSIG(s) ((s).w_stopsig) # endif /* !WSTOPSIG */ # if !defined (WTERMSIG) # define WTERMSIG(s) ((s).w_termsig) # endif /* !WTERMSIG */ # if !defined (WEXITSTATUS) # define WEXITSTATUS(s) ((s).w_retcode) # endif /* !WEXITSTATUS */ # if !defined (WIFCORED) # define WIFCORED(s) ((s).w_coredump) # endif /* !WIFCORED */ #endif /* !_POSIX_VERSION */ #endif /* !_POSIXWAIT_H_ */ |
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/readline In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/readline Added Files: COPYING ChangeLog Makefile.in README STANDALONE ansi_stdlib.h bind.c callback.c chardefs.h compat.c complete.c display.c emacs_keymap.c funmap.c histexpand.c histfile.c histlib.h history.c history.h histsearch.c input.c isearch.c keymaps.c keymaps.h kill.c macro.c mbutil.c misc.c nls.c parens.c posixdir.h posixjmp.h posixstat.h readline.c readline.h rlconf.h rldefs.h rlmbutil.h rlprivate.h rlshell.h rlstdc.h rltty.c rltty.h rltypedefs.h rlwinsize.h savestring.c search.c shell.c signals.c tcap.h terminal.c text.c tilde.c tilde.h undo.c util.c vi_keymap.c vi_mode.c xmalloc.c xmalloc.h Log Message: Pristine source --- NEW FILE: STANDALONE --- This is not to be built as a standalone library to be installed in some public place; get the full readline distribution instead. --- NEW FILE: rldefs.h --- /* rldefs.h -- an attempt to isolate some of the system-specific defines for readline. This should be included after any files that define system-specific constants like _POSIX_VERSION or USG. */ /* Copyright (C) 1987,1989 Free Software Foundation, Inc. This file contains the Readline Library (the Library), a set of routines for providing Emacs style line input to programs that ask for it. The Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if !defined (_RLDEFS_H_) #define _RLDEFS_H_ #if defined (HAVE_CONFIG_H) # include "config.h" #endif #include "rlstdc.h" #if defined (_POSIX_VERSION) && !defined (TERMIOS_MISSING) # define TERMIOS_TTY_DRIVER #else # if defined (HAVE_TERMIO_H) # define TERMIO_TTY_DRIVER # else # define NEW_TTY_DRIVER # endif #endif /* Posix macro to check file in statbuf for directory-ness. This requires that <sys/stat.h> be included before this test. */ #if defined (S_IFDIR) && !defined (S_ISDIR) # define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR) #endif /* Decide which flavor of the header file describing the C library string functions to include and include it. */ #if defined (HAVE_STRING_H) # include <string.h> #else /* !HAVE_STRING_H */ # include <strings.h> #endif /* !HAVE_STRING_H */ #if !defined (strchr) && !defined (__STDC__) extern char *strchr (), *strrchr (); #endif /* !strchr && !__STDC__ */ #if defined (PREFER_STDARG) # include <stdarg.h> #else # if defined (PREFER_VARARGS) # include <varargs.h> # endif #endif #if defined (HAVE_STRCASECMP) #define _rl_stricmp strcasecmp #define _rl_strnicmp strncasecmp #else extern int _rl_stricmp PARAMS((char *, char *)); extern int _rl_strnicmp PARAMS((char *, char *, int)); #endif #if defined (HAVE_STRPBRK) # define _rl_strpbrk(a,b) strpbrk((a),(b)) #else extern char *_rl_strpbrk PARAMS((const char *, const char *)); #endif #if !defined (emacs_mode) # define no_mode -1 # define vi_mode 0 # define emacs_mode 1 #endif #if !defined (RL_IM_INSERT) # define RL_IM_INSERT 1 # define RL_IM_OVERWRITE 0 # # define RL_IM_DEFAULT RL_IM_INSERT #endif /* If you cast map[key].function to type (Keymap) on a Cray, the compiler takes the value of map[key].function and divides it by 4 to convert between pointer types (pointers to functions and pointers to structs are different sizes). This is not what is wanted. */ #if defined (CRAY) # define FUNCTION_TO_KEYMAP(map, key) (Keymap)((int)map[key].function) # define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)((int)(data)) #else # define FUNCTION_TO_KEYMAP(map, key) (Keymap)(map[key].function) # define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)(data) #endif #ifndef savestring #define savestring(x) strcpy ((char *)xmalloc (1 + strlen (x)), (x)) #endif /* Possible values for _rl_bell_preference. */ #define NO_BELL 0 #define AUDIBLE_BELL 1 #define VISIBLE_BELL 2 /* Definitions used when searching the line for characters. */ /* NOTE: it is necessary that opposite directions are inverses */ #define FTO 1 /* forward to */ #define BTO -1 /* backward to */ #define FFIND 2 /* forward find */ #define BFIND -2 /* backward find */ /* Possible values for the found_quote flags word used by the completion functions. It says what kind of (shell-like) quoting we found anywhere in the line. */ #define RL_QF_SINGLE_QUOTE 0x01 #define RL_QF_DOUBLE_QUOTE 0x02 #define RL_QF_BACKSLASH 0x04 #define RL_QF_OTHER_QUOTE 0x08 /* Default readline line buffer length. */ #define DEFAULT_BUFFER_SIZE 256 #if !defined (STREQ) #define STREQ(a, b) (((a)[0] == (b)[0]) && (strcmp ((a), (b)) == 0)) #define STREQN(a, b, n) (((n) == 0) ? (1) \ : ((a)[0] == (b)[0]) && (strncmp ((a), (b), (n)) == 0)) #endif #if !defined (FREE) # define FREE(x) if (x) free (x) #endif #if !defined (SWAP) # define SWAP(s, e) do { int t; t = s; s = e; e = t; } while (0) #endif /* CONFIGURATION SECTION */ #include "rlconf.h" #endif /* !_RLDEFS_H_ */ --- NEW FILE: Makefile.in --- ## -*- text -*- ############################################################# # # # Makefile for the Bash versions of the GNU Readline and History Libraries. # # # ############################################################################# # Copyright (C) 1994 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. srcdir = @srcdir@ VPATH = .:@srcdir@ topdir = @top_srcdir@ BUILD_DIR = @BUILD_DIR@ INSTALL = @INSTALL@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_DATA = @INSTALL_DATA@ CC = @CC@ RANLIB = @RANLIB@ AR = @AR@ ARFLAGS = @ARFLAGS@ RM = rm -f CP = cp MV = mv SHELL = @MAKE_SHELL@ # Programs to make tags files. ETAGS = etags -tw CTAGS = ctags -tw CFLAGS = @CFLAGS@ LOCAL_CFLAGS = @LOCAL_CFLAGS@ CPPFLAGS = @CPPFLAGS@ LDFLAGS = @LDFLAGS@ DEFS = @DEFS@ LOCAL_DEFS = @LOCAL_DEFS@ INCLUDES = -I. -I$(BUILD_DIR) -I$(topdir) -I$(topdir)/lib CCFLAGS = $(DEFS) $(LOCAL_DEFS) $(APP_CFLAGS) $(CPPFLAGS) ${INCLUDES} $(LOCAL_CFLAGS) $(CFLAGS) .c.o: ${RM} $@ $(CC) -c $(CCFLAGS) $< # The name of the main library target. LIBRARY_NAME = libreadline.a # The C code source files for this library. CSOURCES = $(srcdir)/readline.c $(srcdir)/funmap.c $(srcdir)/keymaps.c \ $(srcdir)/vi_mode.c $(srcdir)/parens.c $(srcdir)/rltty.c \ $(srcdir)/complete.c $(srcdir)/bind.c $(srcdir)/isearch.c \ $(srcdir)/display.c $(srcdir)/signals.c $(srcdir)/emacs_keymap.c \ $(srcdir)/vi_keymap.c $(srcdir)/util.c $(srcdir)/kill.c \ $(srcdir)/undo.c $(srcdir)/macro.c $(srcdir)/input.c \ $(srcdir)/callback.c $(srcdir)/terminal.c $(srcdir)/xmalloc.c \ $(srcdir)/history.c $(srcdir)/histsearch.c $(srcdir)/histexpand.c \ $(srcdir)/histfile.c $(srcdir)/nls.c $(srcdir)/search.c \ $(srcdir)/shell.c $(srcdir)/tilde.c $(srcdir)/savestring.c \ $(srcdir)/text.c $(srcdir)/misc.c $(srcdir)/compat.c \ $(srcdir)/mbutil.c # The header files for this library. HSOURCES = readline.h rldefs.h chardefs.h keymaps.h history.h histlib.h \ posixstat.h posixdir.h posixjmp.h tilde.h rlconf.h rltty.h \ ansi_stdlib.h rlstdc.h tcap.h xmalloc.h rlprivate.h rlshell.h \ rltypedefs.h rlmbutil.h HISTOBJ = history.o histexpand.o histfile.o histsearch.o shell.o savestring.o \ mbutil.o TILDEOBJ = tilde.o OBJECTS = readline.o vi_mode.o funmap.o keymaps.o parens.o search.o \ rltty.o complete.o bind.o isearch.o display.o signals.o \ util.o kill.o undo.o macro.o input.o callback.o terminal.o \ text.o nls.o misc.o $(HISTOBJ) $(TILDEOBJ) xmalloc.o compat.o # The texinfo files which document this library. DOCSOURCE = doc/rlman.texinfo doc/rltech.texinfo doc/rluser.texinfo DOCOBJECT = doc/readline.dvi DOCSUPPORT = doc/Makefile DOCUMENTATION = $(DOCSOURCE) $(DOCOBJECT) $(DOCSUPPORT) SUPPORT = Makefile ChangeLog $(DOCSUPPORT) examples/[-a-z.]* SOURCES = $(CSOURCES) $(HSOURCES) $(DOCSOURCE) THINGS_TO_TAR = $(SOURCES) $(SUPPORT) INSTALLED_HEADERS = readline.h chardefs.h keymaps.h history.h tilde.h \ rlstdc.h rlconf.h rltypedefs.h ########################################################################## all: libreadline.a libhistory.a libreadline.a: $(OBJECTS) $(RM) $@ $(AR) $(ARFLAGS) $@ $(OBJECTS) -test -n "$(RANLIB)" && $(RANLIB) $@ libhistory.a: $(HISTOBJ) xmalloc.o $(RM) $@ $(AR) $(ARFLAGS) $@ $(HISTOBJ) xmalloc.o -test -n "$(RANLIB)" && $(RANLIB) $@ documentation: force test -d doc || mkdir doc -( cd doc && $(MAKE) $(MFLAGS) ) # Since tilde.c is shared between readline and bash, make sure we compile # it with the right flags when it's built as part of readline tilde.o: tilde.c rm -f $@ $(CC) $(CCFLAGS) -DREADLINE_LIBRARY -c $(srcdir)/tilde.c force: install: @echo "This version of the readline library should not be installed." uninstall: @echo "This version of the readline library should not be installed." TAGS: force $(ETAGS) $(CSOURCES) $(HSOURCES) tags: force $(CTAGS) $(CSOURCES) $(HSOURCES) clean: force $(RM) $(OBJECTS) *.a -( cd doc && $(MAKE) $(MFLAGS) $@ ) mostlyclean: clean -( cd doc && $(MAKE) $(MFLAGS) $@ ) distclean maintainer-clean: clean -( cd doc && $(MAKE) $(MFLAGS) $@ ) $(RM) Makefile $(RM) TAGS tags # Dependencies bind.o: ansi_stdlib.h posixstat.h bind.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h bind.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h bind.o: history.h rlstdc.h callback.o: rlconf.h ansi_stdlib.h callback.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h callback.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h rlstdc.h compat.o: rlstdc.h complete.o: ansi_stdlib.h posixdir.h posixstat.h complete.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h complete.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h rlstdc.h display.o: ansi_stdlib.h posixstat.h display.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h display.o: tcap.h display.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h display.o: history.h rlstdc.h funmap.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h funmap.o: rlconf.h ansi_stdlib.h rlstdc.h funmap.o: ${BUILD_DIR}/config.h histexpand.o: ansi_stdlib.h histexpand.o: history.h histlib.h rlstdc.h histexpand.o: ${BUILD_DIR}/config.h histfile.o: ansi_stdlib.h histfile.o: history.h histlib.h rlstdc.h histfile.o: ${BUILD_DIR}/config.h history.o: ansi_stdlib.h history.o: history.h histlib.h rlstdc.h history.o: ${BUILD_DIR}/config.h histsearch.o: ansi_stdlib.h histsearch.o: history.h histlib.h rlstdc.h histsearch.o: ${BUILD_DIR}/config.h input.o: ansi_stdlib.h input.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h input.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h rlstdc.h isearch.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h isearch.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h isearch.o: ansi_stdlib.h history.h rlstdc.h keymaps.o: emacs_keymap.c vi_keymap.c keymaps.o: keymaps.h rltypedefs.h chardefs.h rlconf.h ansi_stdlib.h keymaps.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h keymaps.o: ${BUILD_DIR}/config.h rlstdc.h kill.o: ansi_stdlib.h kill.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h kill.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h kill.o: history.h rlstdc.h macro.o: ansi_stdlib.h macro.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h macro.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h macro.o: history.h rlstdc.h mbutil.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h rlmbutil.h mbutil.o: readline.h keymaps.h rltypedefs.h chardefs.h rlstdc.h misc.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h misc.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h misc.o: history.h rlstdc.h ansi_stdlib.h nls.o: ansi_stdlib.h nls.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h nls.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h nls.o: history.h rlstdc.h parens.o: rlconf.h parens.o: ${BUILD_DIR}/config.h parens.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h rlstdc.h readline.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h readline.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h readline.o: history.h rlstdc.h readline.o: posixstat.h ansi_stdlib.h posixjmp.h rltty.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h rltty.o: rltty.h rltty.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h rlstdc.h search.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h search.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h search.o: ansi_stdlib.h history.h rlstdc.h shell.o: ${BUILD_DIR}/config.h ansi_stdlib.h signals.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h signals.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h signals.o: history.h rlstdc.h terminal.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h terminal.o: tcap.h terminal.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h terminal.o: history.h rlstdc.h text.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h text.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h text.o: history.h rlstdc.h ansi_stdlib.h rltty.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h tilde.o: ansi_stdlib.h tilde.o: ${BUILD_DIR}/config.h tilde.o: tilde.h undo.o: ansi_stdlib.h undo.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h undo.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h undo.o: history.h rlstdc.h xmalloc.h util.o: posixjmp.h ansi_stdlib.h util.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h util.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h rlstdc.h vi_mode.o: rldefs.h ${BUILD_DIR}/config.h rlconf.h vi_mode.o: readline.h keymaps.h rltypedefs.h chardefs.h tilde.h vi_mode.o: history.h ansi_stdlib.h rlstdc.h xmalloc.o: ${BUILD_DIR}/config.h ansi_stdlib.h bind.o: rlshell.h histfile.o: rlshell.h nls.o: rlshell.h readline.o: rlshell.h shell.o: rlshell.h terminal.o: rlshell.h histexpand.o: rlshell.h bind.o: rlprivate.h callback.o: rlprivate.h complete.o: rlprivate.h display.o: rlprivate.h input.o: rlprivate.h isearch.o: rlprivate.h kill.o: rlprivate.h macro.o: rlprivate.h mbutil.o: rlprivate.h misc.o: rlprivate.h nls.o: rlprivate.h parens.o: rlprivate.h readline.o: rlprivate.h rltty.o: rlprivate.h search.o: rlprivate.h signals.o: rlprivate.h terminal.o: rlprivate.h text.o: rlprivate.h undo.o: rlprivate.h util.o: rlprivate.h vi_mode.o: rlprivate.h bind.o: xmalloc.h complete.o: xmalloc.h display.o: xmalloc.h funmap.o: xmalloc.h histexpand.o: xmalloc.h histfile.o: xmalloc.h history.o: xmalloc.h input.o: xmalloc.h isearch.o: xmalloc.h keymaps.o: xmalloc.h kill.o: xmalloc.h macro.o: xmalloc.h mbutil.o: xmalloc.h misc.o: xmalloc.h readline.o: xmalloc.h savestring.o: xmalloc.h search.o: xmalloc.h shell.o: xmalloc.h terminal.o: xmalloc.h text.o: xmalloc.h tilde.o: xmalloc.h undo.o: xmalloc.h util.o: xmalloc.h vi_mode.o: xmalloc.h xmalloc.o: xmalloc.h complete.o: rlmbutil.h display.o: rlmbutil.h histexpand.o: rlmbutil.h input.o: rlmbutil.h isearch.o: rlmbutil.h mbutil.o: rlmbutil.h misc.o: rlmbutil.h readline.o: rlmbutil.h search.o: rlmbutil.h text.o: rlmbutil.h vi_mode.o: rlmbutil.h # Rules for deficient makes, like SunOS and Solaris bind.o: bind.c callback.o: callback.c compat.o: compat.c complete.o: complete.c display.o: display.c funmap.o: funmap.c input.o: input.c isearch.o: isearch.c keymaps.o: keymaps.c emacs_keymap.c vi_keymap.c kill.o: kill.c macro.o: macro.c mbutil.o: mbutil.c misc.o: misc.c nls.o: nls.c parens.o: parens.c readline.o: readline.c rltty.o: rltty.c savestring.o: savestring.c search.o: search.c shell.o: shell.c signals.o: signals.c terminal.o: terminal.c text.o: terminal.c tilde.o: tilde.c undo.o: undo.c util.o: util.c vi_mode.o: vi_mode.c xmalloc.o: xmalloc.c histexpand.o: histexpand.c histfile.o: histfile.c history.o: history.c histsearch.o: histsearch.c --- NEW FILE: rltty.c --- /* rltty.c -- functions to prepare and restore the terminal for readline's use. */ /* Copyright (C) 1992 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #define READLINE_LIBRARY #if defined (HAVE_CONFIG_H) # include <config.h> #endif #include <sys/types.h> #include <signal.h> #include <errno.h> #include <stdio.h> #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif /* HAVE_UNISTD_H */ #include "rldefs.h" #if defined (GWINSZ_IN_SYS_IOCTL) # include <sys/ioctl.h> #endif /* GWINSZ_IN_SYS_IOCTL */ #include "rltty.h" #include "readline.h" #include "rlprivate.h" #if !defined (errno) extern int errno; #endif /* !errno */ rl_vintfunc_t *rl_prep_term_function = rl_prep_terminal; rl_voidfunc_t *rl_deprep_term_function = rl_deprep_terminal; static void block_sigint PARAMS((void)); static void release_sigint PARAMS((void)); static void set_winsize PARAMS((int)); /* **************************************************************** */ /* */ /* Signal Management */ /* */ /* **************************************************************** */ #if defined (HAVE_POSIX_SIGNALS) static sigset_t sigint_set, sigint_oset; #else /* !HAVE_POSIX_SIGNALS */ # if defined (HAVE_BSD_SIGNALS) static int sigint_oldmask; # endif /* HAVE_BSD_SIGNALS */ #endif /* !HAVE_POSIX_SIGNALS */ static int sigint_blocked; /* Cause SIGINT to not be delivered until the corresponding call to release_sigint(). */ static void block_sigint () { if (sigint_blocked) return; #if defined (HAVE_POSIX_SIGNALS) sigemptyset (&sigint_set); sigemptyset (&sigint_oset); sigaddset (&sigint_set, SIGINT); sigprocmask (SIG_BLOCK, &sigint_set, &sigint_oset); #else /* !HAVE_POSIX_SIGNALS */ # if defined (HAVE_BSD_SIGNALS) sigint_oldmask = sigblock (sigmask (SIGINT)); # else /* !HAVE_BSD_SIGNALS */ # if defined (HAVE_USG_SIGHOLD) sighold (SIGINT); # endif /* HAVE_USG_SIGHOLD */ # endif /* !HAVE_BSD_SIGNALS */ #endif /* !HAVE_POSIX_SIGNALS */ sigint_blocked = 1; } /* Allow SIGINT to be delivered. */ static void release_sigint () { if (sigint_blocked == 0) return; #if defined (HAVE_POSIX_SIGNALS) sigprocmask (SIG_SETMASK, &sigint_oset, (sigset_t *)NULL); #else # if defined (HAVE_BSD_SIGNALS) sigsetmask (sigint_oldmask); # else /* !HAVE_BSD_SIGNALS */ # if defined (HAVE_USG_SIGHOLD) sigrelse (SIGINT); # endif /* HAVE_USG_SIGHOLD */ # endif /* !HAVE_BSD_SIGNALS */ #endif /* !HAVE_POSIX_SIGNALS */ sigint_blocked = 0; } /* **************************************************************** */ /* */ /* Saving and Restoring the TTY */ /* */ /* **************************************************************** */ /* Non-zero means that the terminal is in a prepped state. */ static int terminal_prepped; static _RL_TTY_CHARS _rl_tty_chars, _rl_last_tty_chars; /* If non-zero, means that this process has called tcflow(fd, TCOOFF) and output is suspended. */ #if defined (__ksr1__) static int ksrflow; #endif /* Dummy call to force a backgrounded readline to stop before it tries to get the tty settings. */ static void set_winsize (tty) int tty; { #if defined (TIOCGWINSZ) struct winsize w; if (ioctl (tty, TIOCGWINSZ, &w) == 0) (void) ioctl (tty, TIOCSWINSZ, &w); #endif /* TIOCGWINSZ */ } #if defined (NEW_TTY_DRIVER) /* Values for the `flags' field of a struct bsdtty. This tells which elements of the struct bsdtty have been fetched from the system and are valid. */ #define SGTTY_SET 0x01 #define LFLAG_SET 0x02 #define TCHARS_SET 0x04 #define LTCHARS_SET 0x08 struct bsdtty { struct sgttyb sgttyb; /* Basic BSD tty driver information. */ int lflag; /* Local mode flags, like LPASS8. */ #if defined (TIOCGETC) struct tchars tchars; /* Terminal special characters, including ^S and ^Q. */ #endif #if defined (TIOCGLTC) struct ltchars ltchars; /* 4.2 BSD editing characters */ #endif int flags; /* Bitmap saying which parts of the struct are valid. */ }; #define TIOTYPE struct bsdtty static TIOTYPE otio; static void save_tty_chars PARAMS((TIOTYPE *)); static int _get_tty_settings PARAMS((int, TIOTYPE *)); static int get_tty_settings PARAMS((int, TIOTYPE *)); static int _set_tty_settings PARAMS((int, TIOTYPE *)); static int set_tty_settings PARAMS((int, TIOTYPE *)); static void prepare_terminal_settings PARAMS((int, TIOTYPE, TIOTYPE *)); static void save_tty_chars (tiop) TIOTYPE *tiop; { _rl_last_tty_chars = _rl_tty_chars; if (tiop->flags & SGTTY_SET) { _rl_tty_chars.t_erase = tiop->sgttyb.sg_erase; _rl_tty_chars.t_kill = tiop->sgttyb.sg_kill; } if (tiop->flags & TCHARS_SET) { _rl_tty_chars.t_intr = tiop->tchars.t_intrc; _rl_tty_chars.t_quit = tiop->tchars.t_quitc; _rl_tty_chars.t_start = tiop->tchars.t_startc; _rl_tty_chars.t_stop = tiop->tchars.t_stopc; _rl_tty_chars.t_eof = tiop->tchars.t_eofc; _rl_tty_chars.t_eol = '\n'; _rl_tty_chars.t_eol2 = tiop->tchars.t_brkc; } if (tiop->flags & LTCHARS_SET) { _rl_tty_chars.t_susp = tiop->ltchars.t_suspc; _rl_tty_chars.t_dsusp = tiop->ltchars.t_dsuspc; _rl_tty_chars.t_reprint = tiop->ltchars.t_rprntc; _rl_tty_chars.t_flush = tiop->ltchars.t_flushc; _rl_tty_chars.t_werase = tiop->ltchars.t_werasc; _rl_tty_chars.t_lnext = tiop->ltchars.t_lnextc; } _rl_tty_chars.t_status = -1; } static int get_tty_settings (tty, tiop) int tty; TIOTYPE *tiop; { set_winsize (tty); tiop->flags = tiop->lflag = 0; if (ioctl (tty, TIOCGETP, &(tiop->sgttyb)) < 0) return -1; tiop->flags |= SGTTY_SET; #if defined (TIOCLGET) if (ioctl (tty, TIOCLGET, &(tiop->lflag)) == 0) tiop->flags |= LFLAG_SET; #endif #if defined (TIOCGETC) if (ioctl (tty, TIOCGETC, &(tiop->tchars)) == 0) tiop->flags |= TCHARS_SET; #endif #if defined (TIOCGLTC) if (ioctl (tty, TIOCGLTC, &(tiop->ltchars)) == 0) tiop->flags |= LTCHARS_SET; #endif return 0; } static int set_tty_settings (tty, tiop) int tty; TIOTYPE *tiop; { if (tiop->flags & SGTTY_SET) { ioctl (tty, TIOCSETN, &(tiop->sgttyb)); tiop->flags &= ~SGTTY_SET; } readline_echoing_p = 1; #if defined (TIOCLSET) if (tiop->flags & LFLAG_SET) { ioctl (tty, TIOCLSET, &(tiop->lflag)); tiop->flags &= ~LFLAG_SET; } #endif #if defined (TIOCSETC) if (tiop->flags & TCHARS_SET) { ioctl (tty, TIOCSETC, &(tiop->tchars)); tiop->flags &= ~TCHARS_SET; } #endif #if defined (TIOCSLTC) if (tiop->flags & LTCHARS_SET) { ioctl (tty, TIOCSLTC, &(tiop->ltchars)); tiop->flags &= ~LTCHARS_SET; } #endif return 0; } static void prepare_terminal_settings (meta_flag, oldtio, tiop) int meta_flag; TIOTYPE oldtio, *tiop; { readline_echoing_p = (oldtio.sgttyb.sg_flags & ECHO); /* Copy the original settings to the structure we're going to use for our settings. */ tiop->sgttyb = oldtio.sgttyb; tiop->lflag = oldtio.lflag; #if defined (TIOCGETC) tiop->tchars = oldtio.tchars; #endif #if defined (TIOCGLTC) tiop->ltchars = oldtio.ltchars; #endif tiop->flags = oldtio.flags; /* First, the basic settings to put us into character-at-a-time, no-echo input mode. */ tiop->sgttyb.sg_flags &= ~(ECHO | CRMOD); tiop->sgttyb.sg_flags |= CBREAK; /* If this terminal doesn't care how the 8th bit is used, then we can use it for the meta-key. If only one of even or odd parity is specified, then the terminal is using parity, and we cannot. */ #if !defined (ANYP) # define ANYP (EVENP | ODDP) #endif if (((oldtio.sgttyb.sg_flags & ANYP) == ANYP) || ((oldtio.sgttyb.sg_flags & ANYP) == 0)) { tiop->sgttyb.sg_flags |= ANYP; /* Hack on local mode flags if we can. */ #if defined (TIOCLGET) # if defined (LPASS8) tiop->lflag |= LPASS8; # endif /* LPASS8 */ #endif /* TIOCLGET */ } #if defined (TIOCGETC) # if defined (USE_XON_XOFF) /* Get rid of terminal output start and stop characters. */ tiop->tchars.t_stopc = -1; /* C-s */ tiop->tchars.t_startc = -1; /* C-q */ /* If there is an XON character, bind it to restart the output. */ if (oldtio.tchars.t_startc != -1) rl_bind_key (oldtio.tchars.t_startc, rl_restart_output); # endif /* USE_XON_XOFF */ /* If there is an EOF char, bind _rl_eof_char to it. */ if (oldtio.tchars.t_eofc != -1) _rl_eof_char = oldtio.tchars.t_eofc; # if defined (NO_KILL_INTR) /* Get rid of terminal-generated SIGQUIT and SIGINT. */ tiop->tchars.t_quitc = -1; /* C-\ */ tiop->tchars.t_intrc = -1; /* C-c */ # endif /* NO_KILL_INTR */ #endif /* TIOCGETC */ #if defined (TIOCGLTC) /* Make the interrupt keys go away. Just enough to make people happy. */ tiop->ltchars.t_dsuspc = -1; /* C-y */ tiop->ltchars.t_lnextc = -1; /* C-v */ #endif /* TIOCGLTC */ } #else /* !defined (NEW_TTY_DRIVER) */ #if !defined (VMIN) # define VMIN VEOF #endif #if !defined (VTIME) # define VTIME VEOL #endif #if defined (TERMIOS_TTY_DRIVER) # define TIOTYPE struct termios # define DRAIN_OUTPUT(fd) tcdrain (fd) # define GETATTR(tty, tiop) (tcgetattr (tty, tiop)) # ifdef M_UNIX # define SETATTR(tty, tiop) (tcsetattr (tty, TCSANOW, tiop)) # else # define SETATTR(tty, tiop) (tcsetattr (tty, TCSADRAIN, tiop)) # endif /* !M_UNIX */ #else # define TIOTYPE struct termio # define DRAIN_OUTPUT(fd) # define GETATTR(tty, tiop) (ioctl (tty, TCGETA, tiop)) # define SETATTR(tty, tiop) (ioctl (tty, TCSETAW, tiop)) #endif /* !TERMIOS_TTY_DRIVER */ static TIOTYPE otio; static void save_tty_chars PARAMS((TIOTYPE *)); static int _get_tty_settings PARAMS((int, TIOTYPE *)); static int get_tty_settings PARAMS((int, TIOTYPE *)); static int _set_tty_settings PARAMS((int, TIOTYPE *)); static int set_tty_settings PARAMS((int, TIOTYPE *)); static void prepare_terminal_settings PARAMS((int, TIOTYPE, TIOTYPE *)); #if defined (FLUSHO) # define OUTPUT_BEING_FLUSHED(tp) (tp->c_lflag & FLUSHO) #else # define OUTPUT_BEING_FLUSHED(tp) 0 #endif static void save_tty_chars (tiop) TIOTYPE *tiop; { _rl_last_tty_chars = _rl_tty_chars; _rl_tty_chars.t_eof = tiop->c_cc[VEOF]; _rl_tty_chars.t_eol = tiop->c_cc[VEOL]; #ifdef VEOL2 _rl_tty_chars.t_eol2 = tiop->c_cc[VEOL2]; #endif _rl_tty_chars.t_erase = tiop->c_cc[VERASE]; #ifdef VWERASE _rl_tty_chars.t_werase = tiop->c_cc[VWERASE]; #endif _rl_tty_chars.t_kill = tiop->c_cc[VKILL]; #ifdef VREPRINT _rl_tty_chars.t_reprint = tiop->c_cc[VREPRINT]; #endif _rl_tty_chars.t_intr = tiop->c_cc[VINTR]; _rl_tty_chars.t_quit = tiop->c_cc[VQUIT]; #ifdef VSUSP _rl_tty_chars.t_susp = tiop->c_cc[VSUSP]; #endif #ifdef VDSUSP _rl_tty_chars.t_dsusp = tiop->c_cc[VDSUSP]; #endif #ifdef VSTART _rl_tty_chars.t_start = tiop->c_cc[VSTART]; #endif #ifdef VSTOP _rl_tty_chars.t_stop = tiop->c_cc[VSTOP]; #endif #ifdef VLNEXT _rl_tty_chars.t_lnext = tiop->c_cc[VLNEXT]; #endif #ifdef VDISCARD _rl_tty_chars.t_flush = tiop->c_cc[VDISCARD]; #endif #ifdef VSTATUS _rl_tty_chars.t_status = tiop->c_cc[VSTATUS]; #endif } #if defined (_AIX) || defined (_AIX41) /* Currently this is only used on AIX */ static void rltty_warning (msg) char *msg; { fprintf (stderr, "readline: warning: %s\n", msg); } #endif #if defined (_AIX) void setopost(tp) TIOTYPE *tp; { if ((tp->c_oflag & OPOST) == 0) { rltty_warning ("turning on OPOST for terminal\r"); tp->c_oflag |= OPOST|ONLCR; } } #endif static int _get_tty_settings (tty, tiop) int tty; TIOTYPE *tiop; { int ioctl_ret; while (1) { ioctl_ret = GETATTR (tty, tiop); if (ioctl_ret < 0) { if (errno != EINTR) return -1; else continue; } if (OUTPUT_BEING_FLUSHED (tiop)) { #if defined (FLUSHO) && defined (_AIX41) rltty_warning ("turning off output flushing"); tiop->c_lflag &= ~FLUSHO; break; #else continue; #endif } break; } return 0; } static int get_tty_settings (tty, tiop) int tty; TIOTYPE *tiop; { set_winsize (tty); if (_get_tty_settings (tty, tiop) < 0) return -1; #if defined (_AIX) setopost(tiop); #endif return 0; } static int _set_tty_settings (tty, tiop) int tty; TIOTYPE *tiop; { while (SETATTR (tty, tiop) < 0) { if (errno != EINTR) return -1; errno = 0; } return 0; } static int set_tty_settings (tty, tiop) int tty; TIOTYPE *tiop; { if (_set_tty_settings (tty, tiop) < 0) return -1; #if 0 #if defined (TERMIOS_TTY_DRIVER) # if defined (__ksr1__) if (ksrflow) { ksrflow = 0; tcflow (tty, TCOON); } # else /* !ksr1 */ tcflow (tty, TCOON); /* Simulate a ^Q. */ # endif /* !ksr1 */ #else ioctl (tty, TCXONC, 1); /* Simulate a ^Q. */ #endif /* !TERMIOS_TTY_DRIVER */ #endif /* 0 */ return 0; } static void prepare_terminal_settings (meta_flag, oldtio, tiop) int meta_flag; TIOTYPE oldtio, *tiop; { readline_echoing_p = (oldtio.c_lflag & ECHO); tiop->c_lflag &= ~(ICANON | ECHO); if ((unsigned char) oldtio.c_cc[VEOF] != (unsigned char) _POSIX_VDISABLE) _rl_eof_char = oldtio.c_cc[VEOF]; #if defined (USE_XON_XOFF) #if defined (IXANY) tiop->c_iflag &= ~(IXON | IXOFF | IXANY); #else /* `strict' Posix systems do not define IXANY. */ tiop->c_iflag &= ~(IXON | IXOFF); #endif /* IXANY */ #endif /* USE_XON_XOFF */ /* Only turn this off if we are using all 8 bits. */ if (((tiop->c_cflag & CSIZE) == CS8) || meta_flag) tiop->c_iflag &= ~(ISTRIP | INPCK); /* Make sure we differentiate between CR and NL on input. */ tiop->c_iflag &= ~(ICRNL | INLCR); #if !defined (HANDLE_SIGNALS) tiop->c_lflag &= ~ISIG; #else tiop->c_lflag |= ISIG; #endif tiop->c_cc[VMIN] = 1; tiop->c_cc[VTIME] = 0; #if defined (FLUSHO) if (OUTPUT_BEING_FLUSHED (tiop)) { tiop->c_lflag &= ~FLUSHO; oldtio.c_lflag &= ~FLUSHO; } #endif /* Turn off characters that we need on Posix systems with job control, just to be sure. This includes ^Y and ^V. This should not really be necessary. */ #if defined (TERMIOS_TTY_DRIVER) && defined (_POSIX_VDISABLE) #if defined (VLNEXT) tiop->c_cc[VLNEXT] = _POSIX_VDISABLE; #endif #if defined (VDSUSP) tiop->c_cc[VDSUSP] = _POSIX_VDISABLE; #endif #endif /* TERMIOS_TTY_DRIVER && _POSIX_VDISABLE */ } #endif /* NEW_TTY_DRIVER */ /* Put the terminal in CBREAK mode so that we can detect key presses. */ void rl_prep_terminal (meta_flag) int meta_flag; { int tty; TIOTYPE tio; if (terminal_prepped) return; /* Try to keep this function from being INTerrupted. */ block_sigint (); tty = fileno (rl_instream); if (get_tty_settings (tty, &tio) < 0) { release_sigint (); return; } otio = tio; save_tty_chars (&otio); prepare_terminal_settings (meta_flag, otio, &tio); if (set_tty_settings (tty, &tio) < 0) { release_sigint (); return; } if (_rl_enable_keypad) _rl_control_keypad (1); fflush (rl_outstream); terminal_prepped = 1; RL_SETSTATE(RL_STATE_TERMPREPPED); release_sigint (); } /* Restore the terminal's normal settings and modes. */ void rl_deprep_terminal () { int tty; if (!terminal_prepped) return; /* Try to keep this function from being interrupted. */ block_sigint (); tty = fileno (rl_instream); if (_rl_enable_keypad) _rl_control_keypad (0); fflush (rl_outstream); if (set_tty_settings (tty, &otio) < 0) { release_sigint (); return; } terminal_prepped = 0; RL_UNSETSTATE(RL_STATE_TERMPREPPED); release_sigint (); } /* **************************************************************** */ /* */ /* Bogus Flow Control */ /* */ /* **************************************************************** */ int rl_restart_output (count, key) int count, key; { int fildes = fileno (rl_outstream); #if defined (TIOCSTART) #if defined (apollo) ioctl (&fildes, TIOCSTART, 0); #else ioctl (fildes, TIOCSTART, 0); #endif /* apollo */ #else /* !TIOCSTART */ # if defined (TERMIOS_TTY_DRIVER) # if defined (__ksr1__) if (ksrflow) { ksrflow = 0; tcflow (fildes, TCOON); } # else /* !ksr1 */ tcflow (fildes, TCOON); /* Simulate a ^Q. */ # endif /* !ksr1 */ # else /* !TERMIOS_TTY_DRIVER */ # if defined (TCXONC) ioctl (fildes, TCXONC, TCOON); # endif /* TCXONC */ # endif /* !TERMIOS_TTY_DRIVER */ #endif /* !TIOCSTART */ return 0; } int rl_stop_output (count, key) int count, key; { int fildes = fileno (rl_instream); #if defined (TIOCSTOP) # if defined (apollo) ioctl (&fildes, TIOCSTOP, 0); # else ioctl (fildes, TIOCSTOP, 0); # endif /* apollo */ #else /* !TIOCSTOP */ # if defined (TERMIOS_TTY_DRIVER) # if defined (__ksr1__) ksrflow = 1; # endif /* ksr1 */ tcflow (fildes, TCOOFF); # else # if defined (TCXONC) ioctl (fildes, TCXONC, TCOON); # endif /* TCXONC */ # endif /* !TERMIOS_TTY_DRIVER */ #endif /* !TIOCSTOP */ return 0; } /* **************************************************************** */ /* */ /* Default Key Bindings */ /* */ /* **************************************************************** */ /* Set the system's default editing characters to their readline equivalents in KMAP. Should be static, now that we have rl_tty_set_default_bindings. */ void rltty_set_default_bindings (kmap) Keymap kmap; { TIOTYPE ttybuff; int tty = fileno (rl_instream); #if defined (NEW_TTY_DRIVER) #define SET_SPECIAL(sc, func) \ do \ { \ int ic; \ ic = sc; \ if (ic != -1 && kmap[(unsigned char)ic].type == ISFUNC) \ kmap[(unsigned char)ic].function = func; \ } \ while (0) if (get_tty_settings (tty, &ttybuff) == 0) { if (ttybuff.flags & SGTTY_SET) { SET_SPECIAL (ttybuff.sgttyb.sg_erase, rl_rubout); SET_SPECIAL (ttybuff.sgttyb.sg_kill, rl_unix_line_discard); } # if defined (TIOCGLTC) if (ttybuff.flags & LTCHARS_SET) { SET_SPECIAL (ttybuff.ltchars.t_werasc, rl_unix_word_rubout); SET_SPECIAL (ttybuff.ltchars.t_lnextc, rl_quoted_insert); } # endif /* TIOCGLTC */ } #else /* !NEW_TTY_DRIVER */ #define SET_SPECIAL(sc, func) \ do \ { \ unsigned char uc; \ uc = ttybuff.c_cc[sc]; \ if (uc != (unsigned char)_POSIX_VDISABLE && kmap[uc].type == ISFUNC) \ kmap[uc].function = func; \ } \ while (0) if (get_tty_settings (tty, &ttybuff) == 0) { SET_SPECIAL (VERASE, rl_rubout); SET_SPECIAL (VKILL, rl_unix_line_discard); # if defined (VLNEXT) && defined (TERMIOS_TTY_DRIVER) SET_SPECIAL (VLNEXT, rl_quoted_insert); # endif /* VLNEXT && TERMIOS_TTY_DRIVER */ # if defined (VWERASE) && defined (TERMIOS_TTY_DRIVER) SET_SPECIAL (VWERASE, rl_unix_word_rubout); # endif /* VWERASE && TERMIOS_TTY_DRIVER */ } #endif /* !NEW_TTY_DRIVER */ } /* New public way to set the system default editing chars to their readline equivalents. */ void rl_tty_set_default_bindings (kmap) Keymap kmap; { rltty_set_default_bindings (kmap); } #if defined (HANDLE_SIGNALS) #if defined (NEW_TTY_DRIVER) int _rl_disable_tty_signals () { return 0; } int _rl_restore_tty_signals () { return 0; } #else static TIOTYPE sigstty, nosigstty; static int tty_sigs_disabled = 0; int _rl_disable_tty_signals () { if (tty_sigs_disabled) return 0; if (_get_tty_settings (fileno (rl_instream), &sigstty) < 0) return -1; nosigstty = sigstty; nosigstty.c_lflag &= ~ISIG; nosigstty.c_iflag &= ~IXON; if (_set_tty_settings (fileno (rl_instream), &nosigstty) < 0) return (_set_tty_settings (fileno (rl_instream), &sigstty)); tty_sigs_disabled = 1; return 0; } int _rl_restore_tty_signals () { int r; if (tty_sigs_disabled == 0) return 0; r = _set_tty_settings (fileno (rl_instream), &sigstty); if (r == 0) tty_sigs_disabled = 0; return r; } #endif /* !NEW_TTY_DRIVER */ #endif /* HANDLE_SIGNALS */ --- NEW FILE: README --- This is the distribution of the Gnu Readline library. See the file STANDALONE for a description of the #defines that can be passed via the makefile to build readline on different systems. The file rlconf.h contains defines that enable and disable certain readline features. --- NEW FILE: shell.c --- /* shell.c -- readline utility functions that are normally provided by bash when readline is linked as part of the shell. */ /* Copyright (C) 1997 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #define READLINE_LIBRARY #if defined (HAVE_CONFIG_H) # include <config.h> #endif #include <sys/types.h> #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif /* HAVE_UNISTD_H */ #if defined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif /* HAVE_STDLIB_H */ #if defined (HAVE_STRING_H) # include <string.h> #else # include <strings.h> #endif /* !HAVE_STRING_H */ #if defined (HAVE_LIMITS_H) # include <limits.h> #endif #include <fcntl.h> #include <pwd.h> #include <stdio.h> #include "rlstdc.h" #include "rlshell.h" #include "xmalloc.h" #if !defined (HAVE_GETPW_DECLS) extern struct passwd *getpwuid PARAMS((uid_t)); #endif /* !HAVE_GETPW_DECLS */ #ifndef NULL # define NULL 0 #endif #ifndef CHAR_BIT # define CHAR_BIT 8 #endif /* Nonzero if the integer type T is signed. */ #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1)) /* Bound on length of the string representing an integer value of type T. Subtract one for the sign bit if T is signed; 302 / 1000 is log10 (2) rounded up; add one for integer division truncation; add one more for a minus sign if t is signed. */ #define INT_STRLEN_BOUND(t) \ ((sizeof (t) * CHAR_BIT - TYPE_SIGNED (t)) * 302 / 1000 \ + 1 + TYPE_SIGNED (t)) /* All of these functions are resolved from bash if we are linking readline as part of bash. */ /* Does shell-like quoting using single quotes. */ char * sh_single_quote (string) char *string; { register int c; char *result, *r, *s; result = (char *)xmalloc (3 + (4 * strlen (string))); r = result; *r++ = '\''; for (s = string; s && (c = *s); s++) { *r++ = c; if (c == '\'') { *r++ = '\\'; /* insert escaped single quote */ *r++ = '\''; *r++ = '\''; /* start new quoted string */ } } *r++ = '\''; *r = '\0'; return (result); } /* Set the environment variables LINES and COLUMNS to lines and cols, respectively. */ void sh_set_lines_and_columns (lines, cols) int lines, cols; { char *b; #if defined (HAVE_PUTENV) b = (char *)xmalloc (INT_STRLEN_BOUND (int) + sizeof ("LINES=") + 1); sprintf (b, "LINES=%d", lines); putenv (b); b = (char *)xmalloc (INT_STRLEN_BOUND (int) + sizeof ("COLUMNS=") + 1); sprintf (b, "COLUMNS=%d", cols); putenv (b); #else /* !HAVE_PUTENV */ # if defined (HAVE_SETENV) b = (char *)xmalloc (INT_STRLEN_BOUND (int) + 1); sprintf (b, "%d", lines); setenv ("LINES", b, 1); b = (char *)xmalloc (INT_STRLEN_BOUND (int) + 1); sprintf (b, "%d", cols); setenv ("COLUMNS", b, 1); # endif /* HAVE_SETENV */ #endif /* !HAVE_PUTENV */ } char * sh_get_env_value (varname) const char *varname; { return ((char *)getenv (varname)); } char * sh_get_home_dir () { char *home_dir; struct passwd *entry; home_dir = (char *)NULL; entry = getpwuid (getuid ()); if (entry) home_dir = entry->pw_dir; return (home_dir); } #if !defined (O_NDELAY) # if defined (FNDELAY) # define O_NDELAY FNDELAY # endif #endif int sh_unset_nodelay_mode (fd) int fd; { int flags, bflags; if ((flags = fcntl (fd, F_GETFL, 0)) < 0) return -1; bflags = 0; #ifdef O_NONBLOCK bflags |= O_NONBLOCK; #endif #ifdef O_NDELAY bflags |= O_NDELAY; #endif if (flags & bflags) { flags &= ~bflags; return (fcntl (fd, F_SETFL, flags)); } return 0; } --- NEW FILE: util.c --- /* util.c -- readline utility functions */ /* Copyright (C) 1987, 1989, 1992 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #define READLINE_LIBRARY #if defined (HAVE_CONFIG_H) # include <config.h> #endif #include <sys/types.h> #include <fcntl.h> #include "posixjmp.h" #if defined (HAVE_UNISTD_H) # include <unistd.h> /* for _POSIX_VERSION */ #endif /* HAVE_UNISTD_H */ #if defined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif /* HAVE_STDLIB_H */ #include <stdio.h> #include <ctype.h> /* System-specific feature definitions and include files. */ #include "rldefs.h" #if defined (TIOCSTAT_IN_SYS_IOCTL) # include <sys/ioctl.h> #endif /* TIOCSTAT_IN_SYS_IOCTL */ /* Some standard library routines. */ #include "readline.h" #include "rlprivate.h" #include "xmalloc.h" /* **************************************************************** */ /* */ /* Utility Functions */ /* */ /* **************************************************************** */ /* Return 0 if C is not a member of the class of characters that belong in words, or 1 if it is. */ int _rl_allow_pathname_alphabetic_chars = 0; static const char *pathname_alphabetic_chars = "/-_=~.#$"; int rl_alphabetic (c) int c; { if (ALPHABETIC (c)) return (1); return (_rl_allow_pathname_alphabetic_chars && strchr (pathname_alphabetic_chars, c) != NULL); } /* How to abort things. */ int _rl_abort_internal () { rl_ding (); rl_clear_message (); _rl_init_argument (); rl_clear_pending_input (); RL_UNSETSTATE (RL_STATE_MACRODEF); while (rl_executing_macro) _rl_pop_executing_macro (); rl_last_func = (rl_command_func_t *)NULL; longjmp (readline_top_level, 1); return (0); } int rl_abort (count, key) int count, key; { return (_rl_abort_internal ()); } int rl_tty_status (count, key) int count, key; { #if defined (TIOCSTAT) ioctl (1, TIOCSTAT, (char *)0); rl_refresh_line (count, key); #else rl_ding (); #endif return 0; } /* Return a copy of the string between FROM and TO. FROM is inclusive, TO is not. */ char * rl_copy_text (from, to) int from, to; { register int length; char *copy; /* Fix it if the caller is confused. */ if (from > to) SWAP (from, to); length = to - from; copy = (char *)xmalloc (1 + length); strncpy (copy, rl_line_buffer + from, length); copy[length] = '\0'; return (copy); } /* Increase the size of RL_LINE_BUFFER until it has enough space to hold LEN characters. */ void rl_extend_line_buffer (len) int len; { while (len >= rl_line_buffer_len) { rl_line_buffer_len += DEFAULT_BUFFER_SIZE; rl_line_buffer = (char *)xrealloc (rl_line_buffer, rl_line_buffer_len); } _rl_set_the_line (); } /* A function for simple tilde expansion. */ int rl_tilde_expand (ignore, key) int ignore, key; { register int start, end; char *homedir, *temp; int len; end = rl_point; start = end - 1; if (rl_point == rl_end && rl_line_buffer[rl_point] == '~') { homedir = tilde_expand ("~"); _rl_replace_text (homedir, start, end); return (0); } else if (rl_line_buffer[start] != '~') { for (; !whitespace (rl_line_buffer[start]) && start >= 0; start--) ; start++; } end = start; do end++; while (whitespace (rl_line_buffer[end]) == 0 && end < rl_end); if (whitespace (rl_line_buffer[end]) || end >= rl_end) end--; /* If the first character of the current word is a tilde, perform tilde expansion and insert the result. If not a tilde, do nothing. */ if (rl_line_buffer[start] == '~') { len = end - start + 1; temp = (char *)xmalloc (len + 1); strncpy (temp, rl_line_buffer + start, len); temp[len] = '\0'; homedir = tilde_expand (temp); free (temp); _rl_replace_text (homedir, start, end); } return (0); } /* **************************************************************** */ /* */ /* String Utility Functions */ /* */ /* **************************************************************** */ /* Determine if s2 occurs in s1. If so, return a pointer to the match in s1. The compare is case insensitive. */ char * _rl_strindex (s1, s2) register const char *s1, *s2; { register int i, l, len; for (i = 0, l = strlen (s2), len = strlen (s1); (len - i) >= l; i++) if (_rl_strnicmp (s1 + i, s2, l) == 0) return ((char *) (s1 + i)); return ((char *)NULL); } #ifndef HAVE_STRPBRK /* Find the first occurrence in STRING1 of any character from STRING2. Return a pointer to the character in STRING1. */ char * _rl_strpbrk (string1, string2) const char *string1, *string2; { register const char *scan; #if defined (HANDLE_MULTIBYTE) mbstate_t ps; register int i, v; memset (&ps, 0, sizeof (mbstate_t)); #endif for (; *string1; string1++) { for (scan = string2; *scan; scan++) { if (*string1 == *scan) return ((char *)string1); } #if defined (HANDLE_MULTIBYTE) if (MB_CUR_MAX > 1 && rl_byte_oriented == 0) { v = _rl_get_char_len (string1, &ps); if (v > 1) string += v - 1; /* -1 to account for auto-increment in loop */ } #endif } return ((char *)NULL); } #endif #if !defined (HAVE_STRCASECMP) /* Compare at most COUNT characters from string1 to string2. Case doesn't matter. */ int _rl_strnicmp (string1, string2, count) char *string1, *string2; int count; { register char ch1, ch2; while (count) { ch1 = *string1++; ch2 = *string2++; if (_rl_to_upper(ch1) == _rl_to_upper(ch2)) count--; else break; } return (count); } /* strcmp (), but caseless. */ int _rl_stricmp (string1, string2) char *string1, *string2; { register char ch1, ch2; while (*string1 && *string2) { ch1 = *string1++; ch2 = *string2++; if (_rl_to_upper(ch1) != _rl_to_upper(ch2)) return (1); } return (*string1 - *string2); } #endif /* !HAVE_STRCASECMP */ /* Stupid comparison routine for qsort () ing strings. */ int _rl_qsort_string_compare (s1, s2) char **s1, **s2; { #if defined (HAVE_STRCOLL) return (strcoll (*s1, *s2)); #else int result; result = **s1 - **s2; if (result == 0) result = strcmp (*s1, *s2); return result; #endif } /* Function equivalents for the macros defined in chardefs.h. */ #define FUNCTION_FOR_MACRO(f) int (f) (c) int c; { return f (c); } FUNCTION_FOR_MACRO (_rl_digit_p) FUNCTION_FOR_MACRO (_rl_digit_value) FUNCTION_FOR_MACRO (_rl_lowercase_p) FUNCTION_FOR_MACRO (_rl_pure_alphabetic) FUNCTION_FOR_MACRO (_rl_to_lower) FUNCTION_FOR_MACRO (_rl_to_upper) FUNCTION_FOR_MACRO (_rl_uppercase_p) /* Backwards compatibility, now that savestring has been removed from all `public' readline header files. */ #undef _rl_savestring char * _rl_savestring (s) const char *s; { return (strcpy ((char *)xmalloc (1 + (int)strlen (s)), (s))); } --- NEW FILE: histsearch.c --- /* histsearch.c -- searching the history list. */ /* Copyright (C) 1989, 1992 Free Software Foundation, Inc. This file contains the GNU History Library (the Library), a set of routines for managing the text of previously typed lines. The Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #define READLINE_LIBRARY #if defined (HAVE_CONFIG_H) # include <config.h> #endif #include <stdio.h> #if defined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif /* HAVE_STDLIB_H */ #if defined (HAVE_UNISTD_H) # ifdef _MINIX # include <sys/types.h> # endif # include <unistd.h> #endif #include "history.h" #include "histlib.h" /* The list of alternate characters that can delimit a history search string. */ char *history_search_delimiter_chars = (char *)NULL; static int history_search_internal PARAMS((const char *, int, int)); /* Search the history for STRING, starting at history_offset. If DIRECTION < 0, then the search is through previous entries, else through subsequent. If ANCHORED is non-zero, the string must appear at the beginning of a history line, otherwise, the string may appear anywhere in the line. If the string is found, then current_history () is the history entry, and the value of this function is the offset in the line of that history entry that the string was found in. Otherwise, nothing is changed, and a -1 is returned. */ static int history_search_internal (string, direction, anchored) const char *string; int direction, anchored; { register int i, reverse; register char *line; register int line_index; int string_len; HIST_ENTRY **the_history; /* local */ i = history_offset; reverse = (direction < 0); /* Take care of trivial cases first. */ if (string == 0 || *string == '\0') return (-1); if (!history_length || ((i == history_length) && !reverse)) return (-1); if (reverse && (i == history_length)) i--; #define NEXT_LINE() do { if (reverse) i--; else i++; } while (0) the_history = history_list (); string_len = strlen (string); while (1) { /* Search each line in the history list for STRING. */ /* At limit for direction? */ if ((reverse && i < 0) || (!reverse && i == history_length)) return (-1); line = the_history[i]->line; line_index = strlen (line); /* If STRING is longer than line, no match. */ if (string_len > line_index) { NEXT_LINE (); continue; } /* Handle anchored searches first. */ if (anchored == ANCHORED_SEARCH) { if (STREQN (string, line, string_len)) { history_offset = i; return (0); } NEXT_LINE (); continue; } /* Do substring search. */ if (reverse) { line_index -= string_len; while (line_index >= 0) { if (STREQN (string, line + line_index, string_len)) { history_offset = i; return (line_index); } line_index--; } } else { register int limit; limit = line_index - string_len + 1; line_index = 0; while (line_index < limit) { if (STREQN (string, line + line_index, string_len)) { history_offset = i; return (line_index); } line_index++; } } NEXT_LINE (); } } /* Do a non-anchored search for STRING through the history in DIRECTION. */ int history_search (string, direction) const char *string; int direction; { return (history_search_internal (string, direction, NON_ANCHORED_SEARCH)); } /* Do an anchored search for string through the history in DIRECTION. */ int history_search_prefix (string, direction) const char *string; int direction; { return (history_search_internal (string, direction, ANCHORED_SEARCH)); } /* Search for STRING in the history list. DIR is < 0 for searching backwards. POS is an absolute index into the history list at which point to begin searching. */ int history_search_pos (string, dir, pos) const char *string; int dir, pos; { int ret, old; old = where_history (); history_set_pos (pos); if (history_search (string, dir) == -1) { history_set_pos (old); return (-1); } ret = where_history (); history_set_pos (old); return ret; } --- NEW FILE: COPYING --- GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contain... [truncated message content] |
Update of /cvsroot/mingw/msys/packages/bash/2.05b/lib/readline/examples In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/lib/readline/examples Added Files: Inputrc Makefile excallback.c fileman.c histexamp.c manexamp.c rl.c rlcat.c rltest.c Log Message: Pristine source --- NEW FILE: rlcat.c --- /* * rlcat - cat(1) using readline * * usage: rlcat */ /* Copyright (C) 1987-2002 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if defined (HAVE_CONFIG_H) # include <config.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include <sys/types.h> #include "posixstat.h" #include <stdio.h> #include <ctype.h> #include <string.h> #include <errno.h> #ifndef errno extern int errno; #endif #if defined (READLINE_LIBRARY) # include "readline.h" # include "history.h" #else # include <readline/readline.h> # include <readline/history.h> #endif extern int optind; extern char *optarg; static int stdcat(); static char *progname; static int vflag; static void usage() { fprintf (stderr, "%s: usage: %s [-vEVN] [filename]\n", progname, progname); } int main (argc, argv) int argc; char **argv; { char *temp; int opt, Vflag, Nflag; progname = strrchr(argv[0], '/'); if (progname == 0) progname = argv[0]; else progname++; vflag = Vflag = Nflag = 0; while ((opt = getopt(argc, argv, "vEVN")) != EOF) { switch (opt) { case 'v': vflag = 1; break; case 'V': Vflag = 1; break; case 'E': Vflag = 0; break; case 'N': Nflag = 1; break; default: usage (); exit (2); } } argc -= optind; argv += optind; if (isatty(0) == 0 || argc || Nflag) return stdcat(argc, argv); rl_variable_bind ("editing-mode", Vflag ? "vi" : "emacs"); while (temp = readline ("")) { if (*temp) add_history (temp); printf ("%s\n", temp); } return (ferror (stdout)); } static int fcopy(fp) FILE *fp; { int c; char *x; while ((c = getc(fp)) != EOF) { if (vflag && isascii ((unsigned char)c) && isprint((unsigned char)c) == 0) { x = rl_untranslate_keyseq (c); if (fputs (x, stdout) != 0) return 1; } else if (putchar (c) == EOF) return 1; } return (ferror (stdout)); } int stdcat (argc, argv) int argc; char **argv; { int i, fd, r; char *s; FILE *fp; if (argc == 0) return (fcopy(stdin)); for (i = 0, r = 1; i < argc; i++) { if (*argv[i] == '-' && argv[i][1] == 0) fp = stdin; else { fp = fopen (argv[i], "r"); if (fp == 0) { fprintf (stderr, "%s: %s: cannot open: %s\n", progname, argv[i], strerror(errno)); continue; } } r = fcopy (fp); if (fp != stdin) fclose(fp); } return r; } --- NEW FILE: histexamp.c --- /* Copyright (C) 1987-2002 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <stdio.h> #ifdef READLINE_LIBRARY # include "history.h" #else # include <readline/history.h> #endif main (argc, argv) int argc; char **argv; { char line[1024], *t; int len, done = 0; line[0] = 0; using_history (); while (!done) { printf ("history$ "); fflush (stdout); t = fgets (line, sizeof (line) - 1, stdin); if (t && *t) { len = strlen (t); if (t[len - 1] == '\n') t[len - 1] = '\0'; } if (!t) strcpy (line, "quit"); if (line[0]) { char *expansion; int result; using_history (); result = history_expand (line, &expansion); if (result) fprintf (stderr, "%s\n", expansion); if (result < 0 || result == 2) { free (expansion); continue; } add_history (expansion); strncpy (line, expansion, sizeof (line) - 1); free (expansion); } if (strcmp (line, "quit") == 0) done = 1; else if (strcmp (line, "save") == 0) write_history ("history_file"); else if (strcmp (line, "read") == 0) read_history ("history_file"); else if (strcmp (line, "list") == 0) { register HIST_ENTRY **the_list; register int i; the_list = history_list (); if (the_list) for (i = 0; the_list[i]; i++) printf ("%d: %s\n", i + history_base, the_list[i]->line); } else if (strncmp (line, "delete", 6) == 0) { int which; if ((sscanf (line + 6, "%d", &which)) == 1) { HIST_ENTRY *entry = remove_history (which); if (!entry) fprintf (stderr, "No such entry %d\n", which); else { free (entry->line); free (entry); } } else { fprintf (stderr, "non-numeric arg given to `delete'\n"); } } } } --- NEW FILE: rltest.c --- /* **************************************************************** */ /* */ /* Testing Readline */ /* */ /* **************************************************************** */ /* Copyright (C) 1987-2002 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if defined (HAVE_CONFIG_H) #include <config.h> #endif #include <stdio.h> #include <sys/types.h> #ifdef READLINE_LIBRARY # include "readline.h" # include "history.h" #else # include <readline/readline.h> # include <readline/history.h> #endif extern HIST_ENTRY **history_list (); main () { char *temp, *prompt; int done; temp = (char *)NULL; prompt = "readline$ "; done = 0; while (!done) { temp = readline (prompt); /* Test for EOF. */ if (!temp) exit (1); /* If there is anything on the line, print it and remember it. */ if (*temp) { fprintf (stderr, "%s\r\n", temp); add_history (temp); } /* Check for `command' that we handle. */ if (strcmp (temp, "quit") == 0) done = 1; if (strcmp (temp, "list") == 0) { HIST_ENTRY **list; register int i; list = history_list (); if (list) { for (i = 0; list[i]; i++) fprintf (stderr, "%d: %s\r\n", i, list[i]->line); } } free (temp); } exit (0); } --- NEW FILE: Inputrc --- # My ~/.inputrc file is in -*- text -*- for easy editing with Emacs. # # Notice the various bindings which are conditionalized depending # on which program is running, or what terminal is active. # # Copyright (C) 1989-2002 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. # In all programs, all terminals, make sure this is bound. "\C-x\C-r": re-read-init-file # Hp terminals (and some others) have ugly default behaviour for C-h. "\C-h": backward-delete-char "\e\C-h": backward-kill-word "\C-xd": dump-functions # In xterm windows, make the arrow keys do the right thing. $if TERM=xterm "\e[A": previous-history "\e[B": next-history "\e[C": forward-char "\e[D": backward-char # alternate arrow key prefix "\eOA": previous-history "\eOB": next-history "\eOC": forward-char "\eOD": backward-char # Under Xterm in Bash, we bind local Function keys to do something useful. $if Bash "\e[11~": "Function Key 1" "\e[12~": "Function Key 2" "\e[13~": "Function Key 3" "\e[14~": "Function Key 4" "\e[15~": "Function Key 5" # I know the following escape sequence numbers are 1 greater than # the function key. Don't ask me why, I didn't design the xterm terminal. "\e[17~": "Function Key 6" "\e[18~": "Function Key 7" "\e[19~": "Function Key 8" "\e[20~": "Function Key 9" "\e[21~": "Function Key 10" $endif $endif # For Bash, all terminals, add some Bash specific hacks. $if Bash "\C-xv": show-bash-version "\C-x\C-e": shell-expand-line # Here is one for editing my path. "\C-xp": "$PATH\C-x\C-e\C-e\"\C-aPATH=\":\C-b" # Make C-x r read my mail in emacs. # "\C-xr": "emacs -f rmail\C-j" $endif # For FTP, different hacks: $if Ftp "\C-xg": "get \M-?" "\C-xt": "put \M-?" "\M-.": yank-last-arg $endif " ": self-insert --- NEW FILE: fileman.c --- /* Copyright (C) 1987-2002 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ /* fileman.c -- A tiny application which demonstrates how to use the GNU Readline library. This application interactively allows users to manipulate files and their modes. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <sys/types.h> #ifdef HAVE_SYS_FILE_H # include <sys/file.h> #endif #include <sys/stat.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include <fcntl.h> #include <stdio.h> #include <errno.h> #if defined (HAVE_STRING_H) # include <string.h> #else /* !HAVE_STRING_H */ # include <strings.h> #endif /* !HAVE_STRING_H */ #ifdef HAVE_STDLIB_H # include <stdlib.h> #endif #ifdef READLINE_LIBRARY # include "readline.h" # include "history.h" #else # include <readline/readline.h> # include <readline/history.h> #endif extern char *xmalloc (); /* The names of functions that actually do the manipulation. */ int com_list PARAMS((char *)); int com_view PARAMS((char *)); int com_rename PARAMS((char *)); int com_stat PARAMS((char *)); int com_pwd PARAMS((char *)); int com_delete PARAMS((char *)); int com_help PARAMS((char *)); int com_cd PARAMS((char *)); int com_quit PARAMS((char *)); /* A structure which contains information on the commands this program can understand. */ typedef struct { char *name; /* User printable name of the function. */ rl_icpfunc_t *func; /* Function to call to do the job. */ char *doc; /* Documentation for this function. */ } COMMAND; COMMAND commands[] = { { "cd", com_cd, "Change to directory DIR" }, { "delete", com_delete, "Delete FILE" }, { "help", com_help, "Display this text" }, { "?", com_help, "Synonym for `help'" }, { "list", com_list, "List files in DIR" }, { "ls", com_list, "Synonym for `list'" }, { "pwd", com_pwd, "Print the current working directory" }, { "quit", com_quit, "Quit using Fileman" }, { "rename", com_rename, "Rename FILE to NEWNAME" }, { "stat", com_stat, "Print out statistics on FILE" }, { "view", com_view, "View the contents of FILE" }, { (char *)NULL, (rl_icpfunc_t *)NULL, (char *)NULL } }; /* Forward declarations. */ char *stripwhite (); COMMAND *find_command (); /* The name of this program, as taken from argv[0]. */ char *progname; /* When non-zero, this global means the user is done using this program. */ int done; char * dupstr (s) char *s; { char *r; r = xmalloc (strlen (s) + 1); strcpy (r, s); return (r); } main (argc, argv) int argc; char **argv; { char *line, *s; progname = argv[0]; initialize_readline (); /* Bind our completer. */ /* Loop reading and executing lines until the user quits. */ for ( ; done == 0; ) { line = readline ("FileMan: "); if (!line) break; /* Remove leading and trailing whitespace from the line. Then, if there is anything left, add it to the history list and execute it. */ s = stripwhite (line); if (*s) { add_history (s); execute_line (s); } free (line); } exit (0); } /* Execute a command line. */ int execute_line (line) char *line; { register int i; COMMAND *command; char *word; /* Isolate the command word. */ i = 0; while (line[i] && whitespace (line[i])) i++; word = line + i; while (line[i] && !whitespace (line[i])) i++; if (line[i]) line[i++] = '\0'; command = find_command (word); if (!command) { fprintf (stderr, "%s: No such command for FileMan.\n", word); return (-1); } /* Get argument to command, if any. */ while (whitespace (line[i])) i++; word = line + i; /* Call the function. */ return ((*(command->func)) (word)); } /* Look up NAME as the name of a command, and return a pointer to that command. Return a NULL pointer if NAME isn't a command name. */ COMMAND * find_command (name) char *name; { register int i; for (i = 0; commands[i].name; i++) if (strcmp (name, commands[i].name) == 0) return (&commands[i]); return ((COMMAND *)NULL); } /* Strip whitespace from the start and end of STRING. Return a pointer into STRING. */ char * stripwhite (string) char *string; { register char *s, *t; for (s = string; whitespace (*s); s++) ; if (*s == 0) return (s); t = s + strlen (s) - 1; while (t > s && whitespace (*t)) t--; *++t = '\0'; return s; } /* **************************************************************** */ /* */ /* Interface to Readline Completion */ /* */ /* **************************************************************** */ char *command_generator PARAMS((const char *, int)); char **fileman_completion PARAMS((const char *, int, int)); /* Tell the GNU Readline library how to complete. We want to try to complete on command names if this is the first word in the line, or on filenames if not. */ initialize_readline () { /* Allow conditional parsing of the ~/.inputrc file. */ rl_readline_name = "FileMan"; /* Tell the completer that we want a crack first. */ rl_attempted_completion_function = fileman_completion; } /* Attempt to complete on the contents of TEXT. START and END bound the region of rl_line_buffer that contains the word to complete. TEXT is the word to complete. We can use the entire contents of rl_line_buffer in case we want to do some simple parsing. Return the array of matches, or NULL if there aren't any. */ char ** fileman_completion (text, start, end) const char *text; int start, end; { char **matches; matches = (char **)NULL; /* If this word is at the start of the line, then it is a command to complete. Otherwise it is the name of a file in the current directory. */ if (start == 0) matches = rl_completion_matches (text, command_generator); return (matches); } /* Generator function for command completion. STATE lets us know whether to start from scratch; without any state (i.e. STATE == 0), then we start at the top of the list. */ char * command_generator (text, state) const char *text; int state; { static int list_index, len; char *name; /* If this is a new word to complete, initialize now. This includes saving the length of TEXT for efficiency, and initializing the index variable to 0. */ if (!state) { list_index = 0; len = strlen (text); } /* Return the next name which partially matches from the command list. */ while (name = commands[list_index].name) { list_index++; if (strncmp (name, text, len) == 0) return (dupstr(name)); } /* If no names matched, then return NULL. */ return ((char *)NULL); } /* **************************************************************** */ /* */ /* FileMan Commands */ /* */ /* **************************************************************** */ /* String to pass to system (). This is for the LIST, VIEW and RENAME commands. */ static char syscom[1024]; /* List the file(s) named in arg. */ com_list (arg) char *arg; { if (!arg) arg = ""; sprintf (syscom, "ls -FClg %s", arg); return (system (syscom)); } com_view (arg) char *arg; { if (!valid_argument ("view", arg)) return 1; #if defined (__MSDOS__) /* more.com doesn't grok slashes in pathnames */ sprintf (syscom, "less %s", arg); #else sprintf (syscom, "more %s", arg); #endif return (system (syscom)); } com_rename (arg) char *arg; { too_dangerous ("rename"); return (1); } com_stat (arg) char *arg; { struct stat finfo; if (!valid_argument ("stat", arg)) return (1); if (stat (arg, &finfo) == -1) { perror (arg); return (1); } printf ("Statistics for `%s':\n", arg); printf ("%s has %d link%s, and is %d byte%s in length.\n", arg, finfo.st_nlink, (finfo.st_nlink == 1) ? "" : "s", finfo.st_size, (finfo.st_size == 1) ? "" : "s"); printf ("Inode Last Change at: %s", ctime (&finfo.st_ctime)); printf (" Last access at: %s", ctime (&finfo.st_atime)); printf (" Last modified at: %s", ctime (&finfo.st_mtime)); return (0); } com_delete (arg) char *arg; { too_dangerous ("delete"); return (1); } /* Print out help for ARG, or for all of the commands if ARG is not present. */ com_help (arg) char *arg; { register int i; int printed = 0; for (i = 0; commands[i].name; i++) { if (!*arg || (strcmp (arg, commands[i].name) == 0)) { printf ("%s\t\t%s.\n", commands[i].name, commands[i].doc); printed++; } } if (!printed) { printf ("No commands match `%s'. Possibilties are:\n", arg); for (i = 0; commands[i].name; i++) { /* Print in six columns. */ if (printed == 6) { printed = 0; printf ("\n"); } printf ("%s\t", commands[i].name); printed++; } if (printed) printf ("\n"); } return (0); } /* Change to the directory ARG. */ com_cd (arg) char *arg; { if (chdir (arg) == -1) { perror (arg); return 1; } com_pwd (""); return (0); } /* Print out the current working directory. */ com_pwd (ignore) char *ignore; { char dir[1024], *s; s = getcwd (dir, sizeof(dir) - 1); if (s == 0) { printf ("Error getting pwd: %s\n", dir); return 1; } printf ("Current directory is %s\n", dir); return 0; } /* The user wishes to quit using this program. Just set DONE non-zero. */ com_quit (arg) char *arg; { done = 1; return (0); } /* Function which tells you that you can't do this. */ too_dangerous (caller) char *caller; { fprintf (stderr, "%s: Too dangerous for me to distribute. Write it yourself.\n", caller); } /* Return non-zero if ARG is a valid argument for CALLER, else print an error message and return zero. */ int valid_argument (caller, arg) char *caller, *arg; { if (!arg || !*arg) { fprintf (stderr, "%s: Argument required.\n", caller); return (0); } return (1); } --- NEW FILE: rl.c --- /* * rl - command-line interface to read a line from the standard input * (or another fd) using readline. * * usage: rl [-p prompt] [-u unit] [-d default] [-n nchars] */ /* Copyright (C) 1987-2002 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #if defined (HAVE_CONFIG_H) # include <config.h> #endif #include <stdio.h> #include <sys/types.h> #include "posixstat.h" #if defined (READLINE_LIBRARY) # include "readline.h" # include "history.h" #else # include <readline/readline.h> # include <readline/history.h> #endif extern int optind; extern char *optarg; #if !defined (strchr) && !defined (__STDC__) extern char *strrchr(); #endif static char *progname; static char *deftext; static int set_deftext () { if (deftext) { rl_insert_text (deftext); deftext = (char *)NULL; rl_startup_hook = (rl_hook_func_t *)NULL; } return 0; } static void usage() { fprintf (stderr, "%s: usage: %s [-p prompt] [-u unit] [-d default] [-n nchars]\n", progname, progname); } int main (argc, argv) int argc; char **argv; { char *temp, *prompt; struct stat sb; int opt, fd, nch; FILE *ifp; progname = strrchr(argv[0], '/'); if (progname == 0) progname = argv[0]; else progname++; /* defaults */ prompt = "readline$ "; fd = nch = 0; deftext = (char *)0; while ((opt = getopt(argc, argv, "p:u:d:n:")) != EOF) { switch (opt) { case 'p': prompt = optarg; break; case 'u': fd = atoi(optarg); if (fd < 0) { fprintf (stderr, "%s: bad file descriptor `%s'\n", progname, optarg); exit (2); } break; case 'd': deftext = optarg; break; case 'n': nch = atoi(optarg); if (nch < 0) { fprintf (stderr, "%s: bad value for -n: `%s'\n", progname, optarg); exit (2); } break; default: usage (); exit (2); } } if (fd != 0) { if (fstat (fd, &sb) < 0) { fprintf (stderr, "%s: %d: bad file descriptor\n", progname, fd); exit (1); } ifp = fdopen (fd, "r"); rl_instream = ifp; } if (deftext && *deftext) rl_startup_hook = set_deftext; if (nch > 0) rl_num_chars_to_read = nch; temp = readline (prompt); /* Test for EOF. */ if (temp == 0) exit (1); printf ("%s\n", temp); exit (0); } --- NEW FILE: manexamp.c --- /* manexamp.c -- The examples which appear in the documentation are here. */ /* Copyright (C) 1987-2002 Free Software Foundation, Inc. This file is part of the GNU Readline Library, a library for reading lines of text with interactive input and history editing. The GNU Readline Library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. The GNU Readline Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #include <stdio.h> #include <readline/readline.h> /* **************************************************************** */ /* */ /* How to Emulate gets () */ /* */ /* **************************************************************** */ /* A static variable for holding the line. */ static char *line_read = (char *)NULL; /* Read a string, and return a pointer to it. Returns NULL on EOF. */ char * rl_gets () { /* If the buffer has already been allocated, return the memory to the free pool. */ if (line_read) { free (line_read); line_read = (char *)NULL; } /* Get a line from the user. */ line_read = readline (""); /* If the line has any text in it, save it on the history. */ if (line_read && *line_read) add_history (line_read); return (line_read); } /* **************************************************************** */ /* */ /* Writing a Function to be Called by Readline. */ /* */ /* **************************************************************** */ /* Invert the case of the COUNT following characters. */ invert_case_line (count, key) int count, key; { register int start, end; start = rl_point; if (count < 0) { direction = -1; count = -count; } else direction = 1; /* Find the end of the range to modify. */ end = start + (count * direction); /* Force it to be within range. */ if (end > rl_end) end = rl_end; else if (end < 0) end = -1; if (start > end) { int temp = start; start = end; end = temp; } if (start == end) return; /* Tell readline that we are modifying the line, so save the undo information. */ rl_modifying (start, end); for (; start != end; start += direction) { if (_rl_uppercase_p (rl_line_buffer[start])) rl_line_buffer[start] = _rl_to_lower (rl_line_buffer[start]); else if (_rl_lowercase_p (rl_line_buffer[start])) rl_line_buffer[start] = _rl_to_upper (rl_line_buffer[start]); } /* Move point to on top of the last character changed. */ rl_point = end - direction; } --- NEW FILE: excallback.c --- /* From: Jeff Solomon <jso...@st...> Date: Fri, 9 Apr 1999 10:13:27 -0700 (PDT) To: ch...@po... Subject: new readline example Message-ID: <140...@mr...> Chet, I've been using readline 4.0. Specifically, I've been using the perl version Term::ReadLine::Gnu. It works great. Anyway, I've been playing around the alternate interface and I wanted to contribute a little C program, callback.c, to you that you could use as an example of the alternate interface in the /examples directory of the readline distribution. My example shows how, using the alternate interface, you can interactively change the prompt (which is very nice imo). Also, I point out that you must roll your own terminal setting when using the alternate interface because readline depreps (using your parlance) the terminal while in the user callback. I try to demostrate what I mean with an example. I've included the program below. To compile, I just put the program in the examples directory and made the appropriate changes to the EXECUTABLES and OBJECTS line and added an additional target 'callback'. I compiled on my Sun Solaris2.6 box using Sun's cc. Let me know what you think. Jeff */ #if defined (HAVE_CONFIG_H) #include <config.h> #endif #include <stdio.h> #include <sys/types.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <termios.h> /* xxx - should make this more general */ #ifdef READLINE_LIBRARY # include "readline.h" #else # include <readline/readline.h> #endif /* This little examples demonstrates the alternate interface to using readline. * In the alternate interface, the user maintains control over program flow and * only calls readline when STDIN is readable. Using the alternate interface, * you can do anything else while still using readline (like talking to a * network or another program) without blocking. * * Specifically, this program highlights two importants features of the * alternate interface. The first is the ability to interactively change the * prompt, which can't be done using the regular interface since rl_prompt is * read-only. * * The second feature really highlights a subtle point when using the alternate * interface. That is, readline will not alter the terminal when inside your * callback handler. So let's so, your callback executes a user command that * takes a non-trivial amount of time to complete (seconds). While your * executing the command, the user continues to type keystrokes and expects them * to be re-echoed on the new prompt when it returns. Unfortunately, the default * terminal configuration doesn't do this. After the prompt returns, the user * must hit one additional keystroke and then will see all of his previous * keystrokes. To illustrate this, compile and run this program. Type "sleep" at * the prompt and then type "bar" before the prompt returns (you have 3 * seconds). Notice how "bar" is re-echoed on the prompt after the prompt * returns? This is what you expect to happen. Now comment out the 4 lines below * the line that says COMMENT LINE BELOW. Recompile and rerun the program and do * the same thing. When the prompt returns, you should not see "bar". Now type * "f", see how "barf" magically appears? This behavior is un-expected and not * desired. */ void process_line(char *line); int change_prompt(void); char *get_prompt(void); int prompt = 1; char prompt_buf[40], line_buf[256]; tcflag_t old_lflag; cc_t old_vtime; struct termios term; int main() { fd_set fds; /* Adjust the terminal slightly before the handler is installed. Disable * canonical mode processing and set the input character time flag to be * non-blocking. */ if( tcgetattr(STDIN_FILENO, &term) < 0 ) { perror("tcgetattr"); exit(1); } old_lflag = term.c_lflag; old_vtime = term.c_cc[VTIME]; term.c_lflag &= ~ICANON; term.c_cc[VTIME] = 1; /* COMMENT LINE BELOW - see above */ if( tcsetattr(STDIN_FILENO, TCSANOW, &term) < 0 ) { perror("tcsetattr"); exit(1); } rl_add_defun("change-prompt", change_prompt, CTRL('t')); rl_callback_handler_install(get_prompt(), process_line); while(1) { FD_ZERO(&fds); FD_SET(fileno(stdin), &fds); if( select(FD_SETSIZE, &fds, NULL, NULL, NULL) < 0) { perror("select"); exit(1); } if( FD_ISSET(fileno(stdin), &fds) ) { rl_callback_read_char(); } } } void process_line(char *line) { if( line == NULL ) { fprintf(stderr, "\n", line); /* reset the old terminal setting before exiting */ term.c_lflag = old_lflag; term.c_cc[VTIME] = old_vtime; if( tcsetattr(STDIN_FILENO, TCSANOW, &term) < 0 ) { perror("tcsetattr"); exit(1); } exit(0); } if( strcmp(line, "sleep") == 0 ) { sleep(3); } else { fprintf(stderr, "|%s|\n", line); } free (line); } int change_prompt(void) { /* toggle the prompt variable */ prompt = !prompt; /* save away the current contents of the line */ strcpy(line_buf, rl_line_buffer); /* install a new handler which will change the prompt and erase the current line */ rl_callback_handler_install(get_prompt(), process_line); /* insert the old text on the new line */ rl_insert_text(line_buf); /* redraw the current line - this is an undocumented function. It invokes the * redraw-current-line command. */ rl_refresh_line(0, 0); } char * get_prompt(void) { /* The prompts can even be different lengths! */ sprintf(prompt_buf, "%s", prompt ? "Hit ctrl-t to toggle prompt> " : "Pretty cool huh?> "); return prompt_buf; } --- NEW FILE: Makefile --- # This is the Makefile for the examples subdirectory of readline. -*- text -*- # # Copyright (C) 1994 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. EXECUTABLES = fileman rltest rl CFLAGS = -g -I../.. -I.. -DREADLINE_LIBRARY LDFLAGS = -g -L.. .c.o: $(CC) $(CFLAGS) -c $< all: $(EXECUTABLES) rl: rl.o $(CC) $(LDFLAGS) -o $@ rl.o -lreadline -ltermcap fileman: fileman.o $(CC) $(LDFLAGS) -o $@ fileman.o -lreadline -ltermcap rltest: rltest.o $(CC) $(LDFLAGS) -o $@ rltest.o -lreadline -ltermcap rlcat: rlcat.o $(CC) $(LDFLAGS) -o $@ rlcat.o -lreadline -ltermcap fileman.o: fileman.c rltest.o: rltest.c rl.o: rl.c rlcat.o: rlcat.c |
Update of /cvsroot/mingw/msys/packages/bash/2.05b/examples/scripts In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/examples/scripts Added Files: adventure.sh bcsh.sh cat.sh center dd-ex.sh fixfiles.bash hanoi.bash inpath krand.bash line-input.bash nohup.bash precedence randomcard.bash scrollbar scrollbar2 self-repro showperm.bash shprompt spin.bash timeout vtree2 vtree3 vtree3a websrv.sh xterm_title zprintf Log Message: Pristine source --- NEW FILE: timeout --- #Newsgroups: comp.unix.admin,comp.unix.solaris,comp.unix.shell #From: gw...@ro... (Geoff Clare) #Subject: Re: timeout -t <sec> <unix command> (Re: How to give rsh a shorter timeout?) #Message-ID: <EoB...@ro...> #Date: Fri, 13 Feb 1998 18:23:52 GMT # # Conversion to bash v2 syntax done by Chet Ramey <ch...@po... # UNTESTED # prog=${0##*/} usage="usage: $prog [-signal] [timeout] [:interval] [+delay] [--] <command>" SIG=-TERM # default signal sent to the process when the timer expires timeout=60 # default timeout interval=15 # default interval between checks if the process is still alive delay=2 # default delay between posting the given signal and # destroying the process (kill -KILL) while : do case $1 in --) shift; break ;; -*) SIG=$1 ;; [0-9]*) timeout=$1 ;; :*) EXPR='..\(.*\)' ; interval=`expr x"$1" : "$EXPR"` ;; +*) EXPR='..\(.*\)' ; delay=`expr x"$1" : "$EXPR"` ;; *) break ;; esac shift done case $# in 0) echo "$prog: $usage" >&2 ; exit 2 ;; esac ( for t in $timeout $delay do while (( $t > $interval )) do sleep $interval kill -0 $$ || exit t=$(( $t - $interval )) done sleep $t kill $SIG $$ && kill -0 $$ || exit SIG=-KILL done ) 2> /dev/null & exec "$@" --- NEW FILE: precedence --- # @(#)precedence_test 1.0 91/07/24 Maarten Litmaath # test of relative precedences for `&&' and `||' operators echo "\`Say' echos its argument. Its return value is of no interest." case `echo -n` in '') Say () { echo -n "$*" ; } ;; *) Say () { echo "$*\c" ; } ;; esac echo "\`Truth' echos its argument and returns a TRUE result." Truth () { Say $1; return 0; } echo "\`False' echos its argument and returns a FALSE result." False () { Say $1; return 1; } echo "" cmd1='$open $test1 && $test2 $close || $test3' cmd2='$test1 || $open $test2 && $test3 $close' grouping_sh= grouping_C='( )' test3='Say 3' for i in 1 2 do eval proto=\$cmd$i for test1 in 'Truth 1' 'False 1' do for test2 in 'Truth 2' 'False 2' do for precedence in sh C do eval set x \$grouping_$precedence shift open=${1-' '} close=${2-' '} eval cmd=\""$proto"\" Say "$cmd output=" output=`eval "$cmd"` Say "$output" read correct || { echo 'Input fubar. Abort.' >&2; exit 1; } test "X$output" = "X$correct" || echo " correct=$correct" echo '' done echo '' done done done << EOF 12 12 123 123 13 13 13 13 13 1 13 1 123 123 12 12 EOF --- NEW FILE: zprintf --- #! /bin/bash # # zprintf - function that calls gawk to do printf for those systems that # don't have a printf executable # # The format and arguments can have trailing commas, just like gawk # # example: # zprintf 'Eat %x %x and suck %x!\n' 57005 48879 64206 # # Chet Ramey # ch...@po... [ $# -lt 1 ] && { echo "zprintf: usage: zprintf format [args ...]" >&2 exit 2 } fmt="${1%,}" shift for a in "$@"; do args="$args,\"${a%,}\"" done gawk "BEGIN { printf \"$fmt\" $args }" --- NEW FILE: cat.sh --- shcat() { while read -r ; do echo "$REPLY" done } if [ -n "$1" ]; then shcat < "$1" else shcat fi --- NEW FILE: websrv.sh --- #!/bin/sh #for instructions or updates go to: #<A HREF="http://math.ucr.edu:8889/">This script's home page</A> #email me questions or comments at: #<A HREF="mailto:in...@ma...">in...@ma...</A> #copyright chris ulrich; This software may be used or modified #in any way so long as this notice remains intact. # # WWW server in sh # Author: Chris Ulrich <ch...@ti...> # INDEX=index.html date=`date` DOCHOME=/home/insom/web-docs BINHOME=/home/insom/web-bin LOGHOME=/home/insom/web-logs LOGFILE=$LOGHOME/access_log #verbose=: verbose=echo exec 2>> $LOGHOME/error_log hheader() { echo "HTTP/1.0 200 OK Server: WebSH/2.00 Connection: close Date: $date" } header() { echo "Content-type: $1 " } no_url() { header "text/plain" echo "No such url $1" } send() { #case "$#" in 2) ;; *) echo eep! | mailx in...@ma... ; exit 3 ;; esac if test -f "$DOCHOME/$2" then header "$1" cat "$DOCHOME/$2" else no_url "$2" fi } LsToHTML() { if test -f "$DOCHOME/$url/.title" then header "text/html; charset=US-ASCII" echo "<pre>" cat "$DOCHOME/$url/.title" echo "</pre>" elif test -f "$DOCHOME/$url/.title.html" then header "text/html; charset=US-ASCII" cat "$DOCHOME/$url/.title.html" else header "text/html; charset=US-ASCII" fi case "$url" in /) ;; *) url="$url/" esac while read link do case $link in *.cgi) ;; *) echo "<A HREF=\"$url$link\">$link</A> <BR>" ;; esac done } read method data $verbose " $date access from ${TCPREMOTEINFO:=NO-IDENT}@${TCPREMOTEHOST:=$TCPREMOTEIP} on local machine $TCPLOCALHOST $method $data " >> $LOGFILE for hopeurl in $data do url="${url}${url:+ }$second" second="$hopeurl" done case "$second" in *[1-9].*) read inheader while case "$inheader" in ?|'') false ;; *) read inheader ;; esac do : done hheader ;; esac case "$url" in *..*) no_url "$url" exit 1 ;; *.txt|*.[ch]) send "text/plain; charset=US-ASCII" "$url" ;; *.html) send "text/html; charset=US-ASCII" "$url" ;; *.cgi) if test -x "$DOCHOME/$url" then read message echo "$message" | "$DOCHOME/$url" else no_url "$url" fi ;; *".cgi?"*) oIFS="$IFS" echo "$url" | { IFS='?' read url QUERY_STRING if test -x "$DOCHOME/$url" then IFS="$oIFS" export QUERY_STRING "$DOCHOME/$url" else no_url "$url" fi } ;; *.[Gg][Ii][Ff]) send "image/gif" "$url" ;; *.[Jj][Pp][Gg]|*.[Jj][Pp][Ee][Gg]) send "image/jpeg" "$url" ;; *.tbl) header "text/html; charset=US-ASCII" echo "<pre>" test -f "$DOCHOME/$url" && tbl < "$DOCHOME/$url" | nroff || no_url "$url" echo "</pre>" ;; *.nroff) header "text/html; charset=US-ASCII" echo "<pre>" test -f "$DOCHOME/$url" && nroff < "$DOCHOME/$url" || no_url "$url" echo "</pre>" ;; *mp[23]) if test -f "$DOCHOME/$url" then header "application/mpstream" echo "+$TCPLOCALIP:${MPSERVPORT:=9001}/$url" else no_url "$url" fi ;; *.[0-9]|*.[0-9][a-z]) header "text/html; charset=US-ASCII" echo "<pre>" if test -f "$DOCHOME/$url" then #nroff -man "$DOCHOME/$url" | $BINHOME/man2html echo "perl at the moment is broken, so man2html doesn't work. Sorry." echo "</pre>" else no_url "$url" fi ;; *.???|*.??) send "unknown/data" "$url" ;; */) if test -d "$DOCHOME/$url" then ls "$DOCHOME/$url" | LsToHTML fi ;; *) if test -f "$DOCHOME/$url" then read filetype < "$DOCHOME/$url" case "$filetype" in \#!/*/*|\#!?/*/*) header "text/plain; charset=US-ASCII" cat "$DOCHOME/$url" ;; '<!*>') header "text/html; charset=US-ASCII" cat "$DOCHOME/$url" ;; *) header "text/html; charset=US-ASCII" echo "<pre>" cat "$DOCHOME/$url" echo "</pre>" ;; esac elif test -f "$DOCHOME/$url/$INDEX" then header "text/html; charset=US-ASCII" cat "$DOCHOME/$url/$INDEX" elif test -d "$DOCHOME/$url" then ls "$DOCHOME/$url" | LsToHTML else no_url "$url" fi ;; esac --- NEW FILE: hanoi.bash --- # Towers of Hanoi in bash # # cribbed from the ksh93 book, example from exercises on page 85 # # Chet Ramey # ch...@po... hanoi() # n from to spare { typeset -i nm1=$1-1 ((nm1>0)) && hanoi $nm1 $2 $4 $3 echo "Move disc $2 to $3" ((nm1>0)) && hanoi $nm1 $4 $3 $2 } case $1 in [1-9]) hanoi $1 1 2 3;; *) echo "${0##*/}: Argument must be from 1 to 9" exit 1;; esac --- NEW FILE: randomcard.bash --- # The following prints a random card from a card deck. # # cribbed from the ksh93 book, example from page 70 # # ch...@po... # declare -i i=0 # load the deck for suit in clubs diamonds hearts spades; do for n in ace 2 3 4 5 6 7 8 9 10 jack queen king; do card[i]="$n of $suit" i=i+1 # let is not required with integer variables done done # and print a random card echo ${card[RANDOM%52]} --- NEW FILE: self-repro --- # self-reproducing script (except for these comment lines -- remove them) # i got this from the ksh93 faq: # http://www.kornshell.com/doc/faq.html # n=" " q="'" x="cat <<-!" y=! z='n="$n" q="$q" x="$x" y=$y z=$q$z$q$n$x$n$z$n$y' cat <<-! n="$n" q="$q" x="$x" y=$y z=$q$z$q$n$x$n$z$n$yb ! --- NEW FILE: scrollbar2 --- #!/bin/bash # # scrollbar - display scrolling text # # usage: scrollbar args # # A cute hack originally from Heiner Steven <hs...@bi...> # # converted from ksh syntax to bash v2 syntax by Chet Ramey WIDTH=${COLUMNS:-80} WMINUS=$(( $WIDTH - 1 )) [ $# -lt 1 ] && set -- TESTING # use the bash-2.02 printf builtin Text=$(printf "%-${WIDTH}s" "$*") while : do printf "%-.${WIDTH}s\r" "$Text" LastC=${Text:${WMINUS}:1} Text="$LastC""${Text%?}" done --- NEW FILE: nohup.bash --- # # BASH VERSION OF nohup COMMAND # ctype() { path=$(builtin type -p $cmd | sed 1q) if [ -n "$path" ]; then echo "$path" return 0 else case "$cmd" in */*) [ -x "$cmd ] && { echo "$cmd" ; return 0; } ;; *) case "$(builtin type -t $cmd)" in "") return 1;; *) echo "$cmd" ; return 0;; esac ;; esac fi return 1 } trap '' HUP # ignore hangup command=$(ctype "$1") oldmask=$(umask) umask u=rw,og= # default mode for nohup.out exec 0< /dev/null # disconnect input if [ -t 1 ]; then # redirect output if necessary if [ -w . ]; then echo 'Sending output to nohup.out' exec >> nohup.out else echo "Sending output to $HOME/nohup.out" exec >> $HOME/nohup.out fi fi umask "$oldmask" # direct unit 2 to a file if [ -t 2 ]; then exec 2>&1 fi # run the command case $command in */*) exec "$@" ;; time) eval "$@" ;; *) "$@" ;; esac --- NEW FILE: vtree3 --- #!/bin/ksh # # Name: dirtree # Programmer: # Hemant T. Shah # Life Insurance Data Processing # July 12 1994 # # Description: # Print directory tree structure as follows: # |___Mail # |___scheduler # |___cics_scripts # |___tar_msdos # |___awk # |___attributes # |___tmp # |___News # |___dosscsi # |___FAQ_xterminal # |___shell_history.Z # |___FAQ_AIX # |___aix_ftp_site # |___hp_software # |___dnload # |___telnet.h # |___msdos # |___tnetd.tar.Z # |___aix # |___hp # |___xkey.c # # Conversion to bash v2 syntax done by Chet Ramey # - removed command substitutions calling `basename' # ProgramName=${0##*/} Path="." ShowAll=1 ShowDir=0 ExpandDirectory() { local object # Local variable cd "$1" for object in $PWD/.??* $PWD/* do if [ -d $object ]; # It is a directory then echo "${indent}|___${object##*/}/" indent="${indent}! " # Add to indentation if [ -x $object ]; then ExpandDirectory $object fi indent=${indent%????} # Remove from indentation elif [ -e $object ]; then if (( ShowAll == 1 )); then echo "${indent}|___${object##*/}" fi fi done } usage() { echo -e "Usage: $ProgramName [-h] [-f] [-d] [path] " echo -e "\t-h ... display this help message." echo -e "\t-f path ... shows all files and directories below path (default)." echo -e "\t-d path ... shows all directories only below path." } while getopts "fd" opt do case $opt in f) ShowAll=1 ;; d) ShowDir=1 ;; *) usage ; exit 2;; esac done shift $(( $OPTIND - 1 )) Path=${1:-.} if [ ! -d "$Path" ]; then echo "$0: error: specified path is not a directory." >&2 exit 1 fi echo "!$Path/" ExpandDirectory $Path --- NEW FILE: krand.bash --- # Originally # # From: bsh...@ne... (Brian S Hiles) # Newsgroups: comp.unix.shell # Subject: Re: getting random numbers # Date: 23 Jan 1997 23:27:30 GMT # Message-ID: <5c8s52$ei...@ti...> # @(#) krand Produces a random number within integer limits # "krand" Korn shell script generates a random number in a # specified range with an optionally specified ``seed'' value. # Author: Peter Turnbull, May 1993 # Modified by: Becca Thomas, January 1994 # changed the optional third argument to a -s option, converted to # bash v2 syntax -- ch...@po... PROGNAME=${0##*/} USAGE="usage: $PROGNAME [-s seed] lower-limit upper-limit" Seed=$$ # Initialize random-number seed value with PID usage() { echo ${PROGNAME}: "$USAGE" >&2 } errexit() { echo ${PROGNAME}: "$@" >&2 exit 1 } # Process command-line arguments: while getopts "s:" opt; do case "$opt" in s) Seed=$OPTARG ;; *) usage ; exit 2;; esac done shift $(($OPTIND - 1)) case $# in 2) Lower=$1; Upper=$2 ;; *) usage ; exit 2;; esac # Check that specified values are integers: expr "$Lower" + 0 >/dev/null 2>&1 [ $? -eq 2 ] && { errexit "lower ($Lower) not an integer"; } expr "$Upper" + 0 >/dev/null 2>&1 [ $? -eq 2 ] && { errexit "upper ($Upper) not an integer"; } expr "$Seed" + 0 >/dev/null 2>&1 [ $? -eq 2 ] && { errexit "seed ($Seed) not an integer"; } # Check that values are in the correct range: if (( "$Lower" < 0 )) || [ ${#Lower} -gt 5 ]; then errexit "lower limit ($Lower) less than zero" fi if (( "$Upper" > 32767 )) || [ ${#Upper} -gt 5 ]; then errexit "upper limit ($Upper) greater than 32767" fi if (( "$Seed" < 0 )) || (( "$Seed" > 32767 )) || [ ${#Seed} -gt 5 ]; then errexit "seed value ($Seed) out of range (0 to 32767)" fi (( "$Upper" <= "$Lower" )) && errexit "upper limit ($Upper) <= lower limit ($Lower)" # Seed the random-number generator: RANDOM=$Seed # Compute value, scaled within range: let rand="$RANDOM % ($Upper - $Lower + 1) + $Lower" # Report result: echo $rand --- NEW FILE: vtree2 --- #!/bin/bash # # vtree - make a tree printout of the specified directory, with disk usage # in 1k blocks # # usage: vtree [-a] [dir] # # Original posted to Usenet sometime in February, 1996 # I believe that the original author is Brian S. Hiles <bsh...@at...> # usage() { echo "vtree: usage: vtree [-a] [dir]" >&2 } while getopts a opt do case "$opt" in a) andfiles=-a ;; *) usage ; exit 2 ;; esac done shift $((OPTIND - 1)) export BLOCKSIZE=1k # 4.4 BSD systems need this [ $# -eq 0 ] && set . while [ $# -gt 0 ] do cd "$1" || { shift; [ $# -ge 1 ] && echo >&2; continue; } echo -n "$PWD" du $andfiles | sort -k 2f | sed \ -e 's/\([^ ]*\) \(.*\)/\2 (\1)/' \ -e "s#^$1##" \ -e 's#[^/]*/\([^/]*\)$#|____\1#' \ -e 's#[^/]*/#| #g' [ $# -gt 1 ] && echo shift done --- NEW FILE: inpath --- #! /bin/sh # # Search $PATH for a file the same name as $1; return TRUE if found. # command=$1 [ -n "$command" ] || exit 1 set `echo $PATH | sed 's/^:/.:/ s/::/:.:/g s/:$/:./ s/:/ /g'` while [ $# -ne 0 ] ; do [ -f $1/$command ] && exit 0 # test -x not universal shift done exit 1 --- NEW FILE: dd-ex.sh --- #!/bin/sh # this is a line editor using only /bin/sh, /bin/dd and /bin/rm # /bin/rm is not really required, but it is nice to clean up temporary files PATH= dd=/bin/dd rm=/bin/rm # temporary files we might need tmp=/tmp/silly.$$ ed=/tmp/ed.$$ trap "$rm -f $tmp $tmp.1 $tmp.2 $tmp.3 $tmp.4 $tmp.5 $tmp.6 $ed.a $ed.b $ed.c; exit" 0 1 2 3 # from now on, no more rm - the above trap is enough unset rm # we do interesting things with IFS, but better save it... saveIFS="$IFS" # in case "echo" is not a shell builtin... Echo () { case "$1" in -n) shift $dd of=$tmp 2>/dev/null <<EOF $@ EOF IFS="+" set `$dd if=$tmp bs=1 of=/dev/null skip=1 2>&1` IFS="$saveIFS" $dd if=$tmp bs=1 count=$1 2>/dev/null ;; *) $dd 2>/dev/null <<EOF $@ EOF ;; esac } # this is used to generate garbage files true () { return 0 } false () { return 1 } zero () { ( trap 'go=false' 13 go=true while $go do $dd "if=$0" case "$?" in 0) ;; *) go=false ;; esac done ) 2>/dev/null } # arithmetic using dd! # add variable n1 n2 n3... # assigns n1+n2+n3+... to variable add () { result="$1" shift $dd if=/dev/null of=$tmp bs=1 2>/dev/null for n in "$@" do case "$n" in 0) ;; *) zero | $dd of=$tmp.1 bs=1 "count=$n" 2>/dev/null ( $dd if=$tmp; $dd if=$tmp.1 ) 2>/dev/null | $dd of=$tmp.2 2>/dev/null $dd if=$tmp.2 of=$tmp 2>/dev/null ;; esac done IFS="+" set `$dd if=$tmp bs=1 of=/dev/null 2>&1` IFS="$saveIFS" eval $result='$1' } # subtract variable n1 n2 # subtracts n2 from n1, assigns result to variable subtract () { result="$1" zero | $dd of=$tmp bs=1 "count=$2" 2>/dev/null IFS="+" set `$dd if=$tmp bs=1 of=/dev/null "skip=$3" 2>&1` IFS="$saveIFS" case "$1" in dd*) set 0 ;; esac eval $result='$1' } # multiply variable n1 n2 # variable = n1 * n2 multiply () { result="$1" zero | $dd "bs=$2" of=$tmp "count=$3" 2>/dev/null IFS="+" set `$dd if=$tmp bs=1 of=/dev/null 2>&1` IFS="$saveIFS" eval $result='$1' } # divide variable n1 n2 # variable = int( n1 / n2 ) divide () { result="$1" zero | $dd bs=1 of=$tmp "count=$2" 2>/dev/null IFS="+" set `$dd if=$tmp "bs=$3" of=/dev/null 2>&1` IFS="$saveIFS" eval $result='$1' } # compare variable n1 n2 sets variable to lt if n1<n2, gt if n1>n2, eq if n1==n2 compare () { res="$1" n1="$2" n2="$3" subtract somename "$n1" "$n2" case "$somename" in 0) ;; *) eval $res=gt; return; esac subtract somename "$n2" "$n1" case "$somename" in 0) ;; *) eval $res=lt; return; esac eval $res=eq } # lt n1 n2 returns true if n1 < n2 lt () { n1="$1" n2="$2" subtract somename "$n2" "$n1" case "$somename" in 0) return 1 ;; esac return 0 } # le n1 n2 returns true if n1 <= n2 le () { n1="$1" n2="$2" subtract somename "$n1" "$n2" case "$somename" in 0) return 0 ;; esac return 1 } # gt n1 n2 returns true if n1 > n2 gt () { n1="$1" n2="$2" subtract somename "$n1" "$n2" case "$somename" in 0) return 1 ;; esac return 0 } # ge n1 n2 returns true if n1 >= n2 ge () { n1="$1" n2="$2" subtract somename "$n2" "$n1" case "$somename" in 0) return 0 ;; esac return 1 } # useful functions for the line editor # open a file - copy it to the buffers open () { file="$1" set `$dd "if=$file" of=/dev/null 2>&1` case "$1" in dd*) return 1 esac # copy the first line to $ed.c go=true len=0 while $go do case "`$dd "if=$file" bs=1 skip=$len count=1 2>/dev/null`" in ?*) go=true ;; *) go=false ;; esac add len 1 $len done # now $len is the length of the first line (including newline) $dd "if=$file" bs=1 count=$len of=$ed.c 2>/dev/null $dd "if=$file" bs=1 skip=$len of=$ed.b 2>/dev/null $dd if=/dev/null of=$ed.a 2>/dev/null lineno=1 } # save a file - copy the buffers to the file save () { # make a backup copy of the original $dd "if=$1" "of=$1.bak" 2>/dev/null # and save ( $dd if=$ed.a; $dd if=$ed.c; $dd if=$ed.b ) > "$1" 2>/dev/null } # replace n1 n2 bla replaces n2 chars of current line, starting n1-th replace () { $dd if=$ed.c of=$tmp.1 bs=1 "count=$1" 2>/dev/null ( $dd if=$ed.c "skip=$1" bs=1 | $dd of=$tmp.2 bs=1 "skip=$2" ) 2>/dev/null shift shift ( $dd if=$tmp.1; Echo -n "$@"; $dd if=$tmp.2 ) > $tmp.3 2>/dev/null $dd if=$tmp.3 of=$ed.c 2>/dev/null } # rstring n s bla # replace the n-th occurence of s with bla rstring () { n="$1" shift; # first we have to find it - this is fun! # we have $tmp.4 => text before string, $tmp.5 => text after $dd if=/dev/null of=$tmp.4 2>/dev/null $dd if=$ed.c of=$tmp.5 2>/dev/null string="$1" shift $dd of=$tmp.6 2>/dev/null <<EOF $@ EOF while : do case "`$dd if=$tmp.5 2>/dev/null`" in $string*) if lt $n 2 then # now we want to replace the string Echo -n "$@" > $tmp.2 Echo -n "$string" > $tmp.1 IFS="+" set `$dd bs=1 if=$tmp.1 of=/dev/null 2>&1` IFS="$saveIFS" slen=$1 IFS="+" ( $dd if=$tmp.4; $dd if=$tmp.2; $dd if=$tmp.5 bs=1 skip=$slen ) \ 2>/dev/null > $tmp $dd if=$tmp of=$ed.c 2>/dev/null return 0 else subtract n $n 1 ( $dd if=$tmp.4; $dd if=$tmp.5 bs=1 count=1 ) > $tmp 2>/dev/null $dd if=$tmp of=$tmp.4 2>/dev/null # and remove it from $tmp.5 $dd if=$tmp.5 of=$tmp bs=1 skip=1 2>/dev/null $dd if=$tmp of=$tmp.5 2>/dev/null fi ;; ?*) # add one more byte... ( $dd if=$tmp.4; $dd if=$tmp.5 bs=1 count=1 ) > $tmp 2>/dev/null $dd if=$tmp of=$tmp.4 2>/dev/null # and remove it from $tmp.5 $dd if=$tmp.5 of=$tmp bs=1 skip=1 2>/dev/null $dd if=$tmp of=$tmp.5 2>/dev/null ;; *) # not found return 1 ;; esac done } # skip to next line next () { add l $lineno 1 ( $dd if=$ed.a; $dd if=$ed.c ) 2>/dev/null > $tmp.3 $dd if=$ed.b of=$tmp.4 2>/dev/null open $tmp.4 $dd if=$tmp.3 of=$ed.a 2>/dev/null lineno=$l } # delete current line delete () { l=$lineno $dd if=$ed.a 2>/dev/null > $tmp.1 $dd if=$ed.b of=$tmp.2 2>/dev/null open $tmp.2 $dd if=$tmp.1 of=$ed.a 2>/dev/null lineno=$l } # insert before current line (without changing current) insert () { ( $dd if=$ed.a; Echo "$@" ) 2>/dev/null > $tmp.1 $dd if=$tmp.1 of=$ed.a 2>/dev/null add lineno $lineno 1 } # previous line prev () { case "$lineno" in 1) ;; *) subtract lineno $lineno 1 # read last line of $ed.a IFS='+' set `$dd if=$ed.a of=/dev/null bs=1 2>&1` IFS="$saveIFS" size=$1 # empty? case "$size" in 0) return ;; esac subtract size $size 1 # skip final newline case "$size" in 0) ;; *) subtract size1 $size 1 case "`$dd if=$ed.a bs=1 skip=$size count=1 2>/dev/null`" in ?*) ;; *) size=$size1 ;; esac ;; esac go=true while $go do case "$size" in 0) go=false ;; *) case "`$dd if=$ed.a bs=1 skip=$size count=1 2>/dev/null`" in ?*) go=true; subtract size $size 1 ;; *) go=false; add size $size 1 ;; esac ;; esac done # now $size is the size of the first n-1 lines # add $ed.c to $ed.b ( $dd if=$ed.c; $dd if=$ed.b ) 2>/dev/null > $tmp.5 $dd if=$tmp.5 of=$ed.b 2>/dev/null # move line to ed.c case "$size" in 0) $dd if=$ed.a of=$ed.c 2>/dev/null $dd if=/dev/null of=$tmp.5 2>/dev/null ;; *) $dd if=$ed.a of=$ed.c bs=1 skip=$size 2>/dev/null $dd if=$ed.a of=$tmp.5 bs=1 count=$size 2>/dev/null ;; esac # move rest to ed.a $dd if=$tmp.5 of=$ed.a 2>/dev/null ;; esac } # goes to a given line goto () { rl="$1" compare bla "$rl" $lineno case "$bla" in eq) return ;; gt) while gt "$rl" $lineno do next done ;; lt) while lt "$rl" $lineno do prev done ;; esac } lineout () { Echo -n "$lineno: " $dd if=$ed.c 2>/dev/null } state=closed name= autoprint=true while true do Echo -n '> ' read cmd arg case "$cmd:$state" in open:open) Echo "There is a file open already" ;; open:*) if open "$arg" then state=open; name="$arg"; $autoprint else Echo "Cannot open $arg" fi ;; new:open) Echo "There is a file open already" ;; new:*) open "$arg" state=open name="$arg" $autoprint ;; close:changed) Echo "Use 'discard' or 'save'" ;; close:closed) Echo "Closed already" ;; close:*) state=closed ;; save:closed) Echo "There isn't a file to save" ;; save:*) case "$arg" in ?*) save "$arg" ;; *) save "$name" ;; esac state=open ;; discard:changed) Echo "Your problem!"; state=closed ;; discard:*) state=closed ;; print:closed) Echo "No current file" ;; print:*) lineout ;; goto:closed) Echo "No current file" ;; goto:*) goto "$arg"; $autoprint ;; next:closed) Echo "No current file" ;; next:*) next; $autoprint ;; prev:closed) Echo "No current file" ;; prev:*) prev; $autoprint ;; name:closed) Echo "No current file" ;; name:*) name="$arg" ;; replace:closed) Echo "No current file" ;; replace:*) if rstring 1 $arg then state=changed; $autoprint else Echo "Not found" fi ;; nreplace:closed) Echo "No current file" ;; nreplace:*) if rstring $arg then state=changed; $autoprint else Echo "Not found" fi ;; delete:closed) Echo "No current file" ;; delete:*) delete; state=changed; $autoprint ;; insert:closed) Echo "No current file" ;; insert:*) insert "$arg"; prev; state=changed; $autoprint ;; quit:changed) Echo "Use 'save' or 'discard'" ;; quit:*) Echo "bye"; exit;; autoprint:*) autoprint="lineout" ;; noprint:*) autoprint="" ;; :*) ;; *) Echo "Command not understood" ;; esac done --- NEW FILE: spin.bash --- #!/bin/bash # # spin.bash -- provide a `spinning wheel' to show progress # # Chet Ramey # ch...@po... # bs=$'\b' chars="|${bs} \\${bs} -${bs} /${bs}" # Infinite loop for demo. purposes while : do for letter in $chars do echo -n ${letter} done done exit 0 --- NEW FILE: adventure.sh --- #!/bin/bash # ash -- "Adventure shell" # last edit: 86/04/21 D A Gwyn # SCCS ID: @(#)ash.sh 1.4 OPATH=$PATH ask() { echo -n "$@" '[y/n] ' read ans case "$ans" in y*|Y*) return 0 ;; *) return 1 ;; esac } CAT=${PAGER:-more} ash_inst() { cat <<- EOF Instructions for the Adventure shell Welcome to the Adventure shell! In this exploration of the UNIX file system, I will act as your eyes and hands. As you move around, I will describe whatever is visible and will carry out your commands. The general form of a command is Verb Object Extra_stuff. Most commands pay no attention to the "Extra_stuff", and many do not need an "Object". A typical command is get all which picks up all files in the current "room" (directory). You can find out what you are carrying by typing the command inventory The command "help" results in a full description of all commands that I understand. To quit the Adventure shell, type quit There are UNIX monsters lurking in the background. These are also known as "commands with arguments". Good luck! EOF } ash_help() { echo "I understand the following commands (synonyms in parentheses):" echo "" echo "change OBJECT to NEW_NAME changes the name of the object" echo "clone OBJECT as NEW_NAME duplicates the object" echo "drop OBJECTS leaves the objects in the room" echo "enter (go) PASSAGE takes the labeled passage" echo "examine OBJECTS describes the objects in detail" echo "feed OBJECT to MONSTER stuffs the object into a UNIX monster" echo "get (take) OBJECTS picks up the specified objects" echo "gripe (bug) report a problem with the Adventure shell" echo "help prints this summary" echo "inventory (i) tells what you are carrying" echo "kill (destroy) OBJECTS destroys the objects" echo "look (l) describes the room, including hidden objects" echo "open (read) OBJECT shows the contents of an object" echo "quit (exit) leaves the Adventure shell" echo "resurrect OBJECTS attempts to restore dead objects" echo "steal OBJECT from MONSTER obtains the object from a UNIX monster" echo "throw OBJECT at daemon feeds the object to the printer daemon" echo "up takes the overhead passage" echo "wake MONSTER awakens a UNIX monster" echo "where (w) tells you where you are" echo "xyzzy moves you to your home" } MAI...@in... PATH=/usr/ucb:/bin:/usr/bin:/usr/local/bin:. export PATH trap 'echo Ouch!' 2 3 #trap '' 18 # disable Berkeley job control #ash_lk(){ echo " $1 " | fgrep " $2 " >&- 2>&-; } ash_lk(){ echo " $1 " | fgrep -q " $2 " >/dev/null 2>&1 ; } ash_pr(){ echo $* | tr ' ' '\012' | pr -5 -t -w75 -l$[ ( $# + 4 ) / 5 ]; } ash_rm(){ echo " $1 " | sed -e "s/ $2 / /" -e 's/^ //' -e 's/ $//'; } # enable history, bang history expansion, and emacs editing set -o history set -o histexpand set -o emacs cd LIM=.limbo # $HOME/$LIM contains "destroyed" objects mkdir $LIM || { echo "ash: cannot mkdir $LIM: exiting" exit 1 } KNAP=.knapsack # $HOME/$KNAP contains objects being "carried" if [ ! -d $KNAP ] then mkdir $KNAP >/dev/null 2>&1 if [ $? = 0 ] then echo 'You found a discarded empty knapsack.' else echo 'You have no knapsack to carry things in.' exit 1 fi else echo 'One moment while I peek in your old knapsack...' fi kn=`echo \`ls -a $KNAP | sed -e '/^\.$/d' -e '/^\.\.$/d'\`` if ask 'Welcome to the Adventure shell! Do you need instructions?' then ash_inst echo -n 'Type a newline to continue: ' read fi wiz=false cha=false prev=$LIM while : do room=`pwd` if [ $room != $prev ] then if [ $room = $HOME ] then echo 'You are in your own home.' else echo "You have entered $room." fi exs= obs= hexs= hobs= f=false for i in `ls -a` do case $i in .|..) ;; .*) if [ -f $i ] then hobs="$hobs $i" elif [ -d $i ] then hexs="$hexs $i" else f=true fi ;; *) if [ -f $i ] then obs="$obs $i" elif [ -d $i ] then exs="$exs $i" else f=true fi ;; esac done if [ "$obs" ] then echo 'This room contains:' ash_pr $obs else echo 'The room looks empty.' fi if [ "$exs" ] then echo 'There are exits labeled:' ash_pr $exs echo 'as well as a passage overhead.' else echo 'There is a passage overhead.' fi if sh -c $f then echo 'There are shadowy figures in the corner.' fi prev=$room fi read -e -p '-advsh> ' verb obj x # prompt is '-advsh> ' if [ $? != 0 ] then verb=quit # EOF fi case $verb in change) if [ "$obj" ] then if ash_lk "$obs $hobs" "$obj" then set -- $x case "$1" in to) if [ "$2" ] then if [ -f $2 ] then echo "You must destroy $2 first." set -- fi if [ "$2" ] then if mv $obj $2 # >&- 2>&- then echo "The $obj shimmers and turns into $2." obs=`ash_rm "$2 $obs" "$obj"` else echo "There is a cloud of smoke but the $obj is unchanged." fi fi else echo 'To what?' fi ;; *) echo "Change $obj to what?" ;; esac else if ash_lk "$kn" "$obj" then echo 'You must drop it first.' else echo "I see no $obj here." fi fi else echo 'Change what?' fi ;; clone) if [ "$obj" ] then if ash_lk "$obs $hobs" "$obj" then if [ ! -r $obj ] then echo "The $obj does not wish to be cloned." else set -- $x case "$1" in as) if [ "$2" ] then if [ -f $2 ] then echo "You must destroy $2 first." else if cp $obj $2 # >&- 2>&- then echo "Poof! When the smoke clears, you see the new $2." obs="$obs $2" else echo 'You hear a dull thud but no clone appears.' fi fi else echo 'As what?' fi ;; *) echo "Clone $obj as what?" ;; esac fi else if ash_lk "$kn" "$obj" then echo 'You must drop it first.' else echo "I see no $obj here." fi fi else echo 'Clone what?' fi ;; drop) if [ "$obj" ] then for it in $obj $x do if ash_lk "$kn" "$it" then if [ -w $it ] then echo "You must destroy $it first." else if mv $HOME/$KNAP/$it $it # >&- 2>&- then echo "$it: dropped." kn=`ash_rm "$kn" "$it"` obs=`echo $it $obs` else echo "The $it is caught in your knapsack." fi fi else echo "You're not carrying the $it!" fi done else echo 'Drop what?' fi ;; enter|go) if [ "$obj" ] then if [ $obj != up ] then if ash_lk "$exs $hexs" "$obj" then if [ -x $obj ] then if cd $obj then echo 'You squeeze through the passage.' else echo "You can't go that direction." fi else echo 'An invisible force blocks your way.' fi else echo 'I see no such passage.' fi else if cd .. then echo 'You struggle upwards.' else echo "You can't reach that high." fi fi else echo 'Which passage?' fi ;; examine) if [ "$obj" ] then if [ $obj = all ] then $obj=`echo $obs $exs` x= fi for it in $obj $x do if ash_lk "$obs $hobs $exs $hexs" "$it" then echo "Upon close inspection of the $it, you see:" ls -ld $it 2>/dev/null if [ $? != 0 ] then echo "-- when you look directly at the $it, it vanishes." fi else if ash_lk "$kn" "$it" then echo 'You must drop it first.' else echo "I see no $it here." fi fi done else echo 'Examine what?' fi ;; feed) if [ "$obj" ] then if ash_lk "$obs $hobs" "$obj" then set -- $x case "$1" in to) if [ "$2" ] then shift if PATH=$OPATH $* <$obj 2>/dev/null then echo "The $1 monster devours your $obj." if rm -f $obj # >&- 2>&- then obs=`ash_rm "$obs" "$obj"` else echo 'But he spits it back up.' fi else echo "The $1 monster holds his nose in disdain." fi else echo 'To what?' fi ;; *) echo "Feed $obj to what?" ;; esac else if ash_lk "$kn" "$obj" then echo 'You must drop it first.' else echo "I see no $obj here." fi fi else echo 'Feed what?' fi ;; get|take) if [ "$obj" ] then if [ $obj = all ] then obj="$obs" x= fi for it in $obj $x do if ash_lk "$obs $hobs" "$it" then if ash_lk "$kn" "$it" then echo 'You already have one.' else if mv $it $HOME/$KNAP/$it # >&- 2>&- then echo "$it: taken." kn="$it $kn" obs=`ash_rm "$obs" "$it"` else echo "The $it is too heavy." fi fi else echo "I see no $it here." fi done else echo 'Get what?' fi ;; gripe|bug) echo 'Please describe the problem and your situation at the time it failed.\nEnd the bug report with a line containing just a Ctrl-D.' cat | mail $MAINT -s 'ash bug' echo 'Thank you!' ;; help) ash_help ;; inventory|i) if [ "$kn" ] then echo 'Your knapsack contains:' ash_pr $kn else echo 'You are poverty-stricken.' fi ;; kill|destroy) if [ "$obj" ] then if [ $obj = all ] then x= if ask "Do you really want to attempt to $verb them all?" then obj=`echo $obs` else echo 'Chicken!' obj= fi fi for it in $obj $x do if ash_lk "$obs $hobs" "$it" then if mv $it $HOME/$LIM # <&- >&- 2>&- then if [ $verb = kill ] then echo "The $it cannot defend himself; he dies." else echo "You have destroyed the $it; it vanishes." fi obs=`ash_rm "$obs" "$it"` else if [ $verb = kill ] then echo "Your feeble blows are no match for the $it." else echo "The $it is indestructible." fi fi else if ash_lk "$kn" "$it" then echo "You must drop the $it first." found=false else echo "I see no $it here." fi fi done else echo 'Kill what?' fi ;; look|l) obs=`echo $obs $hobs` hobs= if [ "$obs" ] then echo 'The room contains:' ash_pr $obs else echo 'The room is empty.' fi exs=`echo $exs $hexs` hexs= if [ "$exs" ] then echo 'There are exits plainly labeled:' ash_pr $exs echo 'and a passage directly overhead.' else echo 'The only exit is directly overhead.' fi ;; magic) if [ "$obj" = mode ] then if sh -c $cha then echo 'You had your chance and you blew it.' else if ask 'Are you a wizard?' then echo -n 'Prove it! Say the magic word: ' read obj if [ "$obj" = armadillo ] then echo 'Yes, master!!' wiz=true else echo "Homie says: I don't think so" cha=true fi else echo "I didn't think so." fi fi else echo 'Nice try.' fi ;; open|read) if [ "$obj" ] then if ash_lk "$obs $hobs" "$obj" then if [ -r $obj ] then if [ -s $obj ] then echo "Opening the $obj reveals:" $CAT < $obj if [ $? != 0 ] then echo '-- oops, you lost the contents!' fi else echo "There is nothing inside the $obj." fi else echo "You do not have the proper tools to open the $obj." fi else if ash_lk "$kn" "$obj" then echo 'You must drop it first.' found=false else echo "I see no $obj here." fi fi else echo 'Open what?' fi ;; quit|exit) if ask 'Do you really want to quit now?' then if [ "$kn" ] then echo 'The contents of your knapsack will still be there next time.' fi rm -rf $HOME/$LIM echo 'See you later!' exit 0 fi ;; resurrect) if [ "$obj" ] then for it in $obj $x do if ash_lk "$obs $hobs" "$it" then echo "The $it is already alive and well." else if mv $HOME/$LIM/$it $it # <&- >&- 2>&- then echo "The $it staggers to his feet." obs=`echo $it $obs` else echo "There are sparks but no $it appears." fi fi done else echo 'Resurrect what?' fi ;; steal) if [ "$obj" ] then if ash_lk "$obs $hobs" "$obj" then echo 'There is already one here.' else set -- $x case "$1" in from) if [ "$2" ] then shift if PATH=$OPATH $* >$obj 2>/dev/null then echo "The $1 monster drops the $obj." obs=`echo $obj $obs` else echo "The $1 monster runs away as you approach." rm -f $obj # >&- 2>&- fi else echo 'From what?' fi ;; *) echo "Steal $obj from what?" ;; esac fi else echo 'Steal what?' fi ;; throw) if [ "$obj" ] then if ash_lk "$obs $hobs" "$obj" then set -- $x case "$1" in at) case "$2" in daemon) if sh -c "lpr -r $obj" then echo "The daemon catches the $obj, turns it into paper,\nand leaves it in the basket." obs=`ash_rm "$obs" "$obj"` else echo "The daemon is nowhere to be found." fi ;; *) echo 'At what?' ;; esac ;; *) echo "Throw $obj at what?" ;; esac else if ash_lk "$kn" "$obj" then echo 'It is in your knapsack.' found=false else echo "I see no $obj here." fi fi else echo 'Throw what?' fi ;; u|up) if cd .. then echo 'You pull yourself up a level.' else echo "You can't reach that high." fi ;; wake) if [ "$obj" ] then echo "You awaken the $obj monster:" PATH=$OPATH $obj $x echo 'The monster slithers back into the darkness.' else echo 'Wake what?' fi ;; w|where) echo "You are in $room." ;; xyzzy) if cd then echo 'A strange feeling comes over you.' else echo 'Your spell fizzles out.' fi ;; *) if [ "$verb" ] then if sh -c $wiz then PATH=$OPATH $verb $obj $x else echo "I don't know how to \"$verb\"." echo 'Type "help" for assistance.' fi else echo 'Say something!' fi ;; esac done --- NEW FILE: shprompt --- # # shprompt -- give a prompt and get an answer satisfying certain criteria # # shprompt [-dDfFsy] prompt # s = prompt for string # f = prompt for filename # F = prompt for full pathname to a file or directory # d = prompt for a directory name # D = prompt for a full pathname to a directory # y = prompt for y or n answer # # Chet Ramey # ch...@in... type=file OPTS=dDfFsy succeed() { echo "$1" exit 0 } while getopts "$OPTS" c do case "$c" in s) type=string ;; f) type=file ;; F) type=path ;; d) type=dir ;; D) type=dirpath ;; y) type=yesno ;; ?) echo "usage: $0 [-$OPTS] prompt" 1>&2 exit 2 ;; esac done if [ "$OPTIND" -gt 1 ] ; then shift $[$OPTIND - 1] fi while : do case "$type" in string) echo -n "$1" 1>&2 read ans || exit 1 if [ -n "$ans" ] ; then succeed "$ans" fi ;; file|path) echo -n "$1" 1>&2 read ans || exit 1 # # use `fn' and eval so that bash will do tilde expansion for # me # eval fn="$ans" case "$fn" in /*) if test -e "$fn" ; then succeed "$fn" else echo "$0: '$fn' does not exist" 1>&2 fi ;; *) if [ "$type" = "path" ] ; then echo "$0: must give full pathname to file" 1>&2 else if test -e "$fn" ; then succeed "$fn" else echo "$0: '$fn' does not exist" 1>&2 fi fi ;; esac ;; dir|dirpath) echo -n "$1" 1>&2 read ans || exit 1 # # use `fn' and eval so that bash will do tilde expansion for # me # eval fn="$ans" case "$fn" in /*) if test -d "$fn" ; then succeed "$fn" elif test -e "$fn" ; then echo "$0 '$fn' is not a directory" 1>&2 else echo "$0: '$fn' does not exist" 1>&2 fi ;; *) if [ "$type" = "dirpath" ] ; then echo "$0: must give full pathname to directory" 1>&2 else if test -d "$fn" ; then succeed "$fn" elif test -e "$fn" ; then echo "$0 '$fn' is not a directory" 1>&2 else echo "$0: '$fn' does not exist" 1>&2 fi fi ;; esac ;; yesno) echo -n "$1" 1>&2 read ans || exit 1 case "$ans" in y|Y|[yY][eE][sS]) succeed "yes" ;; n|N|[nN][oO]) succeed "no" exit 0 ;; *) echo "$0: yes or no required" 1>&2 ;; esac ;; esac done exit 1 --- NEW FILE: center --- #! /bin/bash # # center - center a group of lines # # tabs in the lines might cause this to look a little bit off # # width=${COLUMNS:-80} if [[ $# == 0 ]] then set -- /dev/stdin fi for file do while read -r do printf "%*s\n" $(( (width+${#REPLY})/2 )) "$REPLY" done < $file done exit 0 --- NEW FILE: fixfiles.bash --- #! /bin/bash # # From: c2...@ug... (Kazimir Kylheku) # Newsgroups: comp.unix.shell,comp.os.linux.misc # Subject: GNU Bash Script to fix filenames # Date: 28 Mar 1996 14:54:43 -0800 # Organization: Computer Science, University of B.C., Vancouver, B.C., Canada # #This is a script which takes a list of directories, descends through each one #and ``corrects'' filenames that: # # - contain filename globbing characters: * ? [ ] # - quote characters: ' " # - control characters: 0-31 (127 is not dealt with---oops) # - - or + as the first character # # The GNU version of 'tr' is required. Also requires 'sed'. # # Script to process a given list of directories recursively # and rename each file to something that is reasonable. # # The rules are: # # 1. replace each space, [, ], *, ", and ' character in the name with a # period. # 2. replace each control character 1..31 with a printable character obtained # by adding 64 to the ascii value. ^A becomes A, ^B becomes B and so on. # 3. replace a - or + occuring at the beginning of the name with a # # # 4. if the resulting name has been changed in any way, then # 5. if a file of the new name already exists, then # 6. add a . to the new name and goto step 5. # 7. rename the old name to the new name # # written by Kaz Kylheku <ka...@ca...> # March 1996 # Vancouver, Canada # # requires GNU 'bash', GNU 'tr', and some sort of 'sed' program. # # minimal conversion to bash v2 syntax done by Chet Ramey processfile() { new_name="`echo -n $1 | tr '\173\175\052\077\042\047 ' '.......' | tr '[\000-\037]' '[\100-\137]' | sed -e 's/^-/#/' -e 's/+/#/'`" if [ "$new_name" != "$1" ] ; then while [ -e "$new_name" ] ; do new_name="${new_name}." done echo changing \"$1\" to \"$new_name\" in `pwd` mv -- "$1" "$new_name" fi } processdir() { set -f local savepwd="$PWD" if cd "$1" ; then set +f for file in * ; do set -f if [ "$file" != "." -a "$file" != ".." ] ; then if [ -L "$file" ] ; then echo "skipping symlink" $file in `pwd` elif [ -d "$file" ] ; then processdir "$file" elif [ -f "$file" ] ; then processfile "$file" fi fi done cd "$savepwd" fi } shopt -s nullglob dotglob if [ $# = 0 ] ; then echo "$0: must specify a list of directories" >&2 echo "$0: usage: $0 directory [directory ...]" >&2 exit 2 fi while [ $# != 0 ] ; do processdir "$1" shift done exit 0 --- NEW FILE: vtree3a --- #!/bin/bash # # Name: dirtree # Programmer: # Hemant T. Shah # Life Insurance Data Processing # July 12 1994 # # Description: # Print directory tree structure as follows: # |___Mail # |___scheduler # |___cics_scripts # |___tar_msdos # |___awk # |___attributes # |___tmp # |___News # |___dosscsi # |___FAQ_xterminal # |___shell_history.Z # |___FAQ_AIX # |___aix_ftp_site # |___hp_software # |___dnload # |___telnet.h # |___msdos # |___tnetd.tar.Z # |___aix # |___hp # |___xkey.c # # Conversion to bash v2 syntax done by Chet Ramey # - removed command substitutions calling `basename' # ProgramName=${0##*/} Path="." ShowAll=1 ShowDir=0 ExpandDirectory() { local object # Local variable cd "$1" for object in $PWD/.??* $PWD/* do if [ -d $object ]; # It is a directory then echo "${indent}|___${object##*/}/" indent="${indent}! " # Add to indentation if [ -x $object ]; then ExpandDirectory $object fi indent=${indent%????} # Remove from indentation elif [ -e $object ]; then if (( ShowAll == 1 )); then echo "${indent}|___${object##*/}" fi fi done } usage() { echo -e "Usage: $ProgramName [-h] [-f] [-d] [path] " echo -e "\t-h ... display this help message." echo -e "\t-f path ... shows all files and directories below path (default)." echo -e "\t-d path ... shows all directories only below path." } while getopts "fd" opt do case $opt in f) ShowAll=1 ;; #d) ShowDir=1 ;; d) ShowAll=0 ;; *) usage ; exit 2;; esac done shift $(( $OPTIND - 1 )) Path=${1:-.} if [ ! -d "$Path" ]; then echo "$0: error: specified path is not a directory." >&2 exit 1 fi echo "!$Path/" ExpandDirectory $Path --- NEW FILE: scrollbar --- #!/bin/bash # # scrollbar - display scrolling text # # usage: scrollbar args # # A cute hack originally from Heiner Steven <hs...@bi...> # # converted from ksh syntax to bash v2 syntax by Chet Ramey WIDTH=${COLUMNS:-80} WMINUS=$(( $WIDTH - 1 )) [ $# -lt 1 ] && set -- TESTING # use the bash-2.02 printf builtin Text=$(printf "%-${WIDTH}s" "$*") Text=${Text// /_} while : do printf "%-.${WIDTH}s\r" "$Text" LastC=${Text:${WMINUS}:1} Text="$LastC""${Text%?}" done --- NEW FILE: line-input.bash --- #! /bin/bash # #From: ka...@ca... (Kaz Kylheku) #Newsgroups: comp.unix.shell #Subject: Funky little bash script #Message-ID: <6mspb9$ft...@es...> #Date: Thu, 25 Jun 1998 06:11:39 GMT #Here is something I wrote a few years ago when I was bored one day. #Warning: this contains control characters. # Line input routine for GNU Bourne-Again Shell # plus terminal-control primitives. # # by Kaz Kylheku # June 1996, Vancouver, Canada # # Function to disable canonical input processing. # Terminal modes are saved into variable "savetty" # # function raw { savetty=$(stty -g) stty -icanon -isig -echo -echok -echonl inlcr } # # Function to restore terminal settings from savetty variable # function restore { stty $savetty } # # Set terminal MIN and TIME values. # If the input argument is a zero, set up terminal to wait for # a keystroke indefinitely. If the argument is non-zero, set up # an absolute timeout of that many tenths of a second. The inter-keystroke # timer facility of the terminal driver is not exploited. # function settimeout # $1 = tenths of a second { if [ "$1" = "0" ] ; then min=1 timeout=0 else min=0 timeout="$1" fi stty min $min time $timeout unset min timeout } # # Input a single key using 'dd' and echo it to standard output. # Launching an external program to get a single keystroke is a bit # of a pig, but it's the best you can do! Maybe we could convince the # GNU guys to make 'dd' a bash builtin. # function getkey { eval $1="\"\$(dd bs=1 count=1 2> /dev/null)\"" } # # Input a line of text gracefully. # The first argument is the name of a variable where the input line is # to be stored. If this variable is not empty, its contents are printed # and treated as though the user had entered them. # The second argument gives the maximum length of the input line; if it # is zero, the input is unlimited (bad idea). # ^W is used to delete words # ^R redraws the line at any time by backspacing over it and reprinting it # ^U backspaces to the beginning # ^H or ^? (backspace or del) delete a single character # ^M (enter) terminates the input # all other control keys are ignored and cause a beep when pressed # # function getline { settimeout 0 # No keystroke timeout. save_IFS="$IFS" # Save word delimiter and set it to IFS="" # to null so ${#line} works correctly. eval line=\${$1} # Fetch line contents echo -n "$line" # and print the existing line. while [ 1 ] ; do getkey key # fetch a single keystroke case "$key" in | ) # BS or DEL if [ ${#line} != 0 ] ; then # if line not empty echo -n " " # print destructive BS line="${line%%?}" # chop last character else # else if line empty echo -n # beep the terminal fi ;; ) # kill to line beg while [ ${#line} != 0 ] ; do # while line not empty echo -n " " # print BS, space, BS line="${line%?}" # shorten line by 1 done ;; ) # redraw line linesave="$line" # save the contents while [ ${#line} != 0 ] ; do # kill to line beg echo -n " " line="${line%?}" done echo -n "$linesave" # reprint, restore line="$linesave" unset linesave # forget temp var ;; ) while [ "${line% }" != "$line" -a ${#line} != 0 ] ; do echo -n " " line="${line%?}" done while [ "${line% }" = "$line" -a ${#line} != 0 ] ; do echo -n " " line="${line%?}" done ;; | | | | | | | | | | | ) echo -n # ignore various control characters ;; # with an annoying beep | | | | | | | | | | | | ) echo -n ;; ' ' | | | | | ) echo -n ;; '' ) # Break out of loop on carriage return. echo # Send a newline to the terminal. break # (Also triggered by NUL char!). ;; * ) # Append character to the end of the line. # If length is restricted, and the line is too # long, then beep... if [ "$2" != 0 -a $(( ${#line} >= $2 )) = 1 ] ; then echo -n else # Otherwise add line="$line$key" # the character. echo -n "$key" # And echo it. fi ;; esac done eval $1=\"\$line\" IFS="$save_IFS" unset line save_IFS } # uncomment the lines below to create a standalone test program # echo "Line input demo for the GNU Bourne-Again Shell." echo "Hacked by Kaz Kylheku" echo echo "Use ^H/Backspace/Del to erase, ^W to kill words, ^U to kill the" echo "whole line of input, ^R to redraw the line." echo "Pass an argument to this program to prime the buffer contents" raw echo -n "go: " if [ ${#1} != 0 ] ; then LINE=$1 fi getline LINE 50 restore echo "<$LINE>" --- NEW FILE: xterm_title --- #! /bin/bash # # xterm_title - print the contents of the xterm title bar # # Derived from http://www.clark.net/pub/dickey/xterm/xterm.faq.html#how2_title # P=${0##*/} [ -z "$DISPLAY" ] && { echo "${P}: not running X" >&2 exit 1 } if [ -z "$TERM" ] || [ "$TERM" != "xterm" ]; then echo "${P}: not running in an xterm" >&2 exit 1 fi exec </dev/tty old=$(stty -g) stty raw -echo min 0 time ${1-10} echo -e "\033[21t\c" > /dev/tty IFS='' read -r a stty $old b=${a#???} echo "${b%??}" exit 0 --- NEW FILE: bcsh.sh --- # 1-Feb-86 09:37:35-MST,30567;000000000001 # Return-Path: <uni...@BR...> # Received: from BRL-TGR.ARPA by SIMTEL20.ARPA with TCP; Sat 1 Feb 86 09:36:16-MST # Received: from usenet by TGR.BRL.ARPA id a002623; 1 Feb 86 9:33 EST # From: chris <ch...@gl...> # Newsgroups: net.sources # Subject: Improved Bcsh (Bourne Shell Cshell-Emulator) # Message-ID: <21...@gl...> # Date: 30 Jan 86 17:34:26 GMT # To: uni...@BR... # # This is a new, improved version of my Bourne shell cshell-emulator. # The code has been cleaned up quite a bit, and a couple of new features # added (now supports 'noclobber' and 'iclobber' variables). A bug with # 'eval' that caused "illegal I/O" error messages on vanilla V7 shells has # also been fixed. # I have posted the program in its entirety because a context diff of the # old and new versions was longer than the new version... [...1215 lines suppressed...] esac # The next commented-out line sets the prompt to include the command # number -- you should only un-comment this if it is the ONLY thing # you ever want as your prompt, because it will override attempts # to set PS1 from the command level. If you want the command number # in your prompt without sacrificing the ability to change the prompt # later, replace the default setting for PS1 before the beginning of # the main loop with the following: PS1='echo -n "${cmdno}% "' # Doing it this way is, however, slower than the simple version below. PS1="${cmdno}% " getcmd=yes echoit=no exclaim=no done exit 0 # Christine Robertson {linus, ihnp4, decvax}!utzoo!globetek!chris --- NEW FILE: showperm.bash --- #Newsgroups: comp.unix.shell #From: gw...@ro... (Geoff Clare) #Subject: Re: Determining permissions on a file #Message-ID: <Dr7...@ro...> #Date: Fri, 10 May 1996 17:23:56 GMT #Here's a bit of Korn shell that converts the symbolic permissions produced #by "ls -l" into octal, using only shell builtins. How to create a script #combining this with an "ls -l" is left as an exercise... # # # Converted to Bash v2 syntax by Chet Ramey <ch...@po...> # # usage: showperm modestring # # example: showperm '-rwsr-x--x' # [ -z "$1" ] && { echo "showperm: usage: showperm modestring" >&2 exit 2 } tmode="$1" typeset -i omode sbits typeset pmode # check for set-uid, etc. bits sbits=0 case $tmode in ???[sS]*) (( sbits += 8#4000 )) ;; # set-uid ??????[sSl]*) (( sbits += 8#2000 )) ;; # set-gid or mand. lock ?????????[tT]*) (( sbits += 8#1000 )) ;; # sticky esac omode=0 while : do tmode=${tmode#?} case $tmode in "") break ;; [-STl]*) (( omode *= 2 )) ;; [rwxst]*) (( omode = omode*2 + 1 )) ;; *) echo "$0: first letter of \"$tmode\" is unrecognized" >&2 (( omode *= 2 )) ;; esac done (( omode += sbits )) printf "0%o\n" $omode |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:33
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/examples/loadables/perl In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/examples/loadables/perl Added Files: Makefile.in README bperl.c iperl.c Log Message: Pristine source --- NEW FILE: iperl.c --- #include <EXTERN.h> /* from the Perl distribution */ #include <perl.h> /* from the Perl distribution */ extern void xs_init _((void)); static PerlInterpreter *iperl; /*** The Perl interpreter ***/ int perl_main(int argc, char **argv, char **env) { int r; iperl = perl_alloc(); perl_construct(iperl); perl_parse(iperl, xs_init, argc, argv, (char **)NULL); r = perl_run(iperl); PerlIO_flush(PerlIO_stdout()); PerlIO_flush(PerlIO_stderr()); perl_destruct(iperl); perl_free(iperl); return (r); } --- NEW FILE: README --- This illustrates how to build a perl interpreter into bash. It's not especially useful; more a proof of concept (it provides none of the bash internals to the perl interpreter, for example). This *may* require adding "-rpath /path/to/perl/CORE" and -lperl options when compiling bash itself. --- NEW FILE: Makefile.in --- # # Makefile for builtin perl interpreter # # # Copyright (C) 1998 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. # Include some boilerplate Gnu makefile definitions. prefix = @prefix@ exec_prefix = @exec_prefix@ bindir = @bindir@ libdir = @libdir@ infodir = @infodir@ includedir = @includedir@ topdir = @top_srcdir@ BUILD_DIR = @BUILD_DIR@ srcdir = @srcdir@ VPATH = .:@srcdir@ @SET_MAKE@ CC = @CC@ RM = rm -f SHELL = @MAKE_SHELL@ PERL5 = perl5 CFLAGS = @CFLAGS@ # # These values are generated for configure by ${topdir}/support/shobj-conf. # If your system is not supported by that script, but includes facilities for # dynamic loading of shared objects, please update the script and send the # changes to bas...@gn.... # SHOBJ_CC = @SHOBJ_CC@ SHOBJ_CFLAGS = @SHOBJ_CFLAGS@ SHOBJ_LD = @SHOBJ_LD@ SHOBJ_LDFLAGS = @SHOBJ_LDFLAGS@ SHOBJ_XLDFLAGS = @SHOBJ_XLDFLAGS@ SHOBJ_LIBS = @SHOBJ_LIBS@ SHOBJ_STATUS = @SHOBJ_STATUS@ # Values used for compiling the perl files PERL_LDOPTS = `${PERL5} -MExtUtils::Embed -e ldopts` PERL_CFLAGS = ${CCFLAGS} `${PERL5} -MExtUtils::Embed -e ccopts` SRC = bperl.c iperl.c perlxsi.c OBJ = bperl.o iperl.o perlxsi.o BUILTIN = bperl5 INC = -I. -I.. -I$(topdir) -I$(topdir)/lib -I$(topdir)/builtins \ -I$(topdir)/include -I$(BUILD_DIR) -I$(BUILD_DIR)/lib \ -I$(BUILD_DIR)/builtins ${BUILTIN}: ${OBJ} ${RM} $@ ${SHOBJ_LD} ${SHOBJ_LDFLAGS} ${SHOBJ_XLDFLAGS} -o $@ ${OBJ} ${PERL_LDOPTS} ${SHOBJ_LIBS} bperl.o: bperl.c ${RM} $@ $(SHOBJ_CC) $(SHOBJ_CFLAGS) $(CFLAGS) $(INC) -c -o $@ ${srcdir}/bperl.c iperl.o: iperl.c ${RM} $@ $(SHOBJ_CC) ${SHOBJ_CFLAGS} $(PERL_CFLAGS) -c -o $@ ${srcdir}/iperl.c perlxsi.c: ${PERL5} -MExtUtils::Embed -e xsinit -- -o $@ perlxsi.o: perlxsi.c ${RM} $@ ${SHOBJ_CC} ${SHOBJ_CFLAGS} $(PERL_CFLAGS) -c -o $@ perlxsi.c clean mostlyclean: ${RM} ${OBJ} ${RM} ${BUILTIN} distclean maintainer-clean: clean ${RM} perlxsi.c --- NEW FILE: bperl.c --- /* * perl builtin */ #include <config.h> #include <fcntl.h> #include <errno.h> #include "builtins.h" #include "shell.h" #ifndef errno extern int errno; #endif extern char **make_builtin_argv (); extern char **export_env; extern int perl_main(); bperl_builtin(list) WORD_LIST *list; { char **v; int c, r; v = make_builtin_argv(list, &c); r = perl_main(c, v, export_env); free(v); return r; } char *bperl_doc[] = { "An interface to a perl5 interpreter.", (char *)0 }; struct builtin bperl_struct = { "bperl", bperl_builtin, BUILTIN_ENABLED, bperl_doc, "bperl [perl options] [file ...]", 0 }; |
|
From: Earnie B. <ea...@us...> - 2005-05-22 10:13:33
|
Update of /cvsroot/mingw/msys/packages/bash/2.05b/examples/bashdb In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10360/2.05b/examples/bashdb Added Files: PERMISSION bashdb bashdb.el Log Message: Pristine source --- NEW FILE: bashdb --- #! /bin/bash # bashdb - Bash shell debugger # # Adapted from an idea in O'Reilly's `Learning the Korn Shell' # Copyright (C) 1993-1994 O'Reilly and Associates, Inc. # Copyright (C) 1998, 1999, 2001 Gary V. Vaughan <gv...@te...>> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # NOTE: # # This program requires bash 2.x. # If bash 2.x is installed as "bash2", you can invoke bashdb like this: # # DEBUG_SHELL=/bin/bash2 /bin/bash2 bashdb script.sh # TODO: # # break [regexp] # cond [break] [condition] # tbreak [regexp|+lines] # restart # Variable watchpoints # Instrument `source' and `.' files in $_potbelliedpig # be cleverer about lines we allow breakpoints to be set on # break [function_name] echo 'Bash Debugger version 1.2.4' export _dbname=${0##*/} if test $# -lt 1; then echo "$_dbname: Usage: $_dbname filename" >&2 exit 1 fi _guineapig=$1 if test ! -r $1; then echo "$_dbname: Cannot read file '$_guineapig'." >&2 exit 1 fi shift __debug=${TMPDIR-/tmp}/bashdb.$$ sed -e '/^# bashdb - Bash shell debugger/,/^# -- DO NOT DELETE THIS LINE -- /d' "$0" > $__debug cat $_guineapig >> $__debug exec ${DEBUG_SHELL-bash} $__debug $_guineapig "$@" exit 1 # -- DO NOT DELETE THIS LINE -- The program depends on it #bashdb preamble # $1 name of the original guinea pig script __debug=$0 _guineapig=$1 __steptrap_calls=0 shift shopt -s extglob # turn on extglob so we can parse the debugger funcs function _steptrap { local i=0 _curline=$1 if (( ++__steptrap_calls > 1 && $_curline == 1 )); then return fi if [ -n "$_disps" ]; then while (( $i < ${#_disps[@]} )) do if [ -n "${_disps[$i]}" ]; then _msg "${_disps[$i]}: \c" eval _msg ${_disps[$i]} fi let i=$i+1 done fi if (( $_trace )); then _showline $_curline fi if (( $_steps >= 0 )); then let _steps="$_steps - 1" fi if _at_linenumbp ; then _msg "Reached breakpoint at line $_curline" _showline $_curline _cmdloop elif [ -n "$_brcond" ] && eval $_brcond; then _msg "Break condition $_brcond true at line $_curline" _showline $_curline _cmdloop elif (( $_steps == 0 )); then # Assuming a real script will have the "#! /bin/sh" at line 1, # assume that when $_curline == 1 we are inside backticks. if (( ! $_trace )); then _msg "Stopped at line $_curline" _showline $_curline fi _cmdloop fi } function _setbp { local i f line _x if [ -z "$1" ]; then _listbp return fi eval "$_seteglob" if [[ $1 == *(\+)[1-9]*([0-9]) ]]; then case $1 in +*) # normalize argument, then double it (+2 -> +2 + 2 = 4) _x=${1##*([!1-9])} # cut off non-numeric prefix _x=${x%%*([!0-9])} # cut off non-numeric suffix f=$(( $1 + $_x )) ;; *) f=$(( $1 )) ;; esac # find the next valid line line="${_lines[$f]}" while _invalidbreakp $f do (( f++ )) line="${_lines[$f]}" done if (( $f != $1 )) then _msg "Line $1 is not a valid breakpoint" fi if [ -n "${_lines[$f]}" ]; then _linebp[$1]=$1; _msg "Breakpoint set at line $f" else _msg "Breakpoints can only be set on executable lines" fi else _msg "Please specify a numeric line number" fi eval "$_resteglob" } function _listbp { local i if [ -n "$_linebp" ]; then _msg "Breakpoints:" for i in ${_linebp[*]}; do _showline $i done else _msg "No breakpoints have been set" fi } function _clearbp { local i if [ -z "$1" ]; then read -e -p "Delete all breakpoints? " case $REPLY in [yY]*) unset _linebp[*] _msg "All breakpoints have been cleared" ;; esac return 0 fi eval "$_seteglob" if [[ $1 == [1-9]*([0-9]) ]]; then unset _linebp[$1] _msg "Breakpoint cleared at line $1" else _msg "Please specify a numeric line number" fi eval "$_resteglob" } function _setbc { if (( $# > 0 )); then _brcond=$@ _msg "Break when true: $_brcond" else _brcond= _msg "Break condition cleared" fi } function _setdisp { if [ -z "$1" ]; then _listdisp else _disps[${#_disps[@]}]="$1" if (( ${#_disps[@]} < 10 )) then _msg " ${#_disps[@]}: $1" else _msg "${#_disps[@]}: $1" fi fi } function _listdisp { local i=0 j if [ -n "$_disps" ]; then while (( $i < ${#_disps[@]} )) do let j=$i+1 if (( ${#_disps[@]} < 10 )) then _msg " $j: ${_disps[$i]}" else _msg "$j: ${_disps[$i]}" fi let i=$j done else _msg "No displays have been set" fi } function _cleardisp { if (( $# < 1 )) ; then read -e -p "Delete all display expressions? " case $REPLY in [Yy]*) unset _disps[*] _msg "All breakpoints have been cleared" ;; esac return 0 fi eval "$_seteglob" if [[ $1 == [1-9]*([0-9]) ]]; then unset _disps[$1] _msg "Display $i has been cleared" else _listdisp _msg "Please specify a numeric display number" fi eval "$_resteglob" } # usage _ftrace -u funcname [funcname...] function _ftrace { local _opt=-t _tmsg="enabled" _func if [[ $1 == -u ]]; then _opt=+t _tmsg="disabled" shift fi for _func; do declare -f $_opt $_func _msg "Tracing $_tmsg for function $_func" done } function _cmdloop { local cmd args while read -e -p "bashdb> " cmd args; do test -n "$cmd" && history -s "$cmd $args" # save on history list test -n "$cmd" || { set $_lastcmd; cmd=$1; shift; args=$*; } if [ -n "$cmd" ] then case $cmd in b|br|bre|brea|break) _setbp $args _lastcmd="break $args" ;; co|con) _msg "ambiguous command: '$cmd', condition, continue?" ;; cond|condi|condit|conditi|conditio|condition) _setbc $args _lastcmd="condition $args" ;; c|cont|conti|contin|continu|continue) _lastcmd="continue" return ;; d) _msg "ambiguous command: '$cmd', delete, display?" ;; de|del|dele|delet|delete) _clearbp $args _lastcmd="delete $args" ;; di|dis|disp|displ|displa|display) _setdisp $args _lastcmd="display $args" ;; f|ft|ftr|ftra|ftrace) _ftrace $args _lastcmd="ftrace $args" ;; \?|h|he|hel|help) _menu _lastcmd="help" ;; l|li|lis|list) _displayscript $args # _lastcmd is set in the _displayscript function ;; p|pr|pri|prin|print) _examine $args _lastcmd="print $args" ;; q|qu|qui|quit) exit ;; s|st|ste|step|n|ne|nex|next) let _steps=${args:-1} _lastcmd="next $args" return ;; t|tr|tra|trac|trace) _xtrace ;; u|un|und|undi|undis|undisp|undispl|undispla|undisplay) _cleardisp $args _lastcmd="undisplay $args" ;; !*) eval ${cmd#!} $args _lastcmd="$cmd $args" ;; *) _msg "Invalid command: '$cmd'" ;; esac fi done } function _at_linenumbp { [[ -n ${_linebp[$_curline]} ]] } function _invalidbreakp { local line=${_lines[$1]} # XXX - should use shell patterns if test -z "$line" \ || expr "$line" : '[ \t]*#.*' > /dev/null \ || expr "$line" : '[ \t]*;;[ \t]*$' > /dev/null \ || expr "$line" : '[ \t]*[^)]*)[ \t]*$' > /dev/null \ || expr "$line" : '[ \t]*;;[ \t]*#.**$' > /dev/null \ || expr "$line" : '[ \t]*[^)]*)[ \t]*;;[ \t]*$' > /dev/null \ || expr "$line" : '[ \t]*[^)]*)[ \t]*;;*[ \t]*#.*$' > /dev/null then return 0 fi return 1 } function _examine { if [ -n "$*" ]; then _msg "$args: \c" eval _msg $args else _msg "Nothing to print" fi } function _displayscript { local i j start end bp cl if (( $# == 1 )); then # list 5 lines on either side of $1 if [ $1 = "%" ]; then let start=1 let end=${#_lines[@]} else let start=$1-5 let end=$1+5 fi elif (( $# > 1 )); then # list between start and end if [ $1 = "^" ]; then let start=1 else let start=$1 fi if [ $2 = "\$" ]; then let end=${#_lines[@]} else let end=$2 fi else # list 5 lines on either side of current line let start=$_curline-5 let end=$_curline+5 fi # normalize start and end if (( $start < 1 )); then start=1 fi if (( $end > ${#_lines[@]} )); then end=${#_lines[@]} fi cl=$(( $end - $start )) if (( $cl > ${LINES-24} )); then pager=${PAGER-more} else pager=cat fi i=$start ( while (( $i <= $end )); do _showline $i let i=$i+1 done ) 2>&1 | $pager # calculate the next block of lines start=$(( $end + 1 )) end=$(( $start + 11 )) if (( $end > ${#_lines[@]} )) then end=${#_lines[@]} fi _lastcmd="list $start $end" } function _xtrace { let _trace="! $_trace" if (( $_trace )); then _msg "Execution trace on" else _msg "Execution trace off" fi } function _msg { echo -e "$@" >&2 } function _showline { local i=0 bp=' ' line=$1 cl=' ' if [[ -n ${_linebp[$line]} ]]; then bp='*' fi if (( $_curline == $line )); then cl=">" fi if (( $line < 100 )); then _msg "$_guineapig:$line $bp $cl${_lines[$line]}" elif (( $line < 10 )); then _msg "$_guineapig:$line $bp $cl${_lines[$line]}" elif (( $line > 0 )); then _msg "$_guineapig:$line $bp $cl${_lines[$line]}" fi } function _cleanup { rm -f $__debug $_potbelliedpig 2> /dev/null } function _menu { _msg 'bashdb commands: break N set breakpoint at line N break list breakpoints & break condition condition foo set break condition to foo condition clear break condition delete N clear breakpoint at line N delete clear all breakpoints display EXP evaluate and display EXP for each debug step display show a list of display expressions undisplay N remove display expression N list N M display all lines of script between N and M list N display 5 lines of script either side of line N list display 5 lines if script either side of current line continue continue execution upto next breakpoint next [N] execute [N] statements (default 1) print expr prints the value of an expression trace toggle execution trace on/off ftrace [-u] func make the debugger step into function FUNC (-u turns off tracing FUNC) help print this menu ! string passes string to a shell quit quit' } shopt -u extglob HISTFILE=~/.bashdb_history set -o history set +H # strings to save and restore the setting of `extglob' in debugger functions # that need it _seteglob='local __eopt=-u ; shopt -q extglob && __eopt=-s ; shopt -s extglob' _resteglob='shopt $__eopt extglob' _linebp=() let _trace=0 let _i=1 # Be careful about quoted newlines _potbelliedpig=${TMPDIR-/tmp}/$_guineapig.$$ sed 's,\\$,\\\\,' $_guineapig > $_potbelliedpig _msg "Reading source from file: $_guineapig" while read; do _lines[$_i]=$REPLY let _i=$_i+1 done < $_potbelliedpig trap _cleanup EXIT # Assuming a real script will have the "#! /bin/sh" at line 1, # don't stop at line 1 on the first run let _steps=1 LINENO=-1 trap '_steptrap $LINENO' DEBUG --- NEW FILE: bashdb.el --- ;;; bashdb.el --- Grand Unified Debugger mode for running bashdb ;; Copyright (C) 2000, 2001 Masatake YAMATO ;; Author: Masatake YAMATO <je...@gy...> ;; This program is free software; you can redistribute it and/or modify it ;; under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 2 of the License, or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program; if not, write to the Free Software Foundation, ;; Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;; Commentary: ;; This program may run on Emacs 21.0.91 and XEmacs 21.1. ;; ;; Put ;; (autoload 'bashdb "bashdb" "Run bashdb" t nil) ;; to your .emacs. ;; M-x bashdb ;; Run bashdb (like this): bashdb target.sh ;; ;; About bashdb: ;; You can get bashdb from ;; http://www.oranda.demon.co.uk/development.html ;; ;; bashdb.el is based on perldb in gud.el in XEmacs 21.1. ;; Revision: ;; $Revision: 1.1 $ ;; $Log: bashdb.el,v $ ;; Revision 1.1 2005/05/22 10:13:17 earnie ;; Pristine source ;; ;; Revision 1.6 2001/01/06 12:18:06 masata-y ;; Write note about XEmacs. ;; ;; ;;; Code: (require 'gud) ;; User customizable variable (defcustom gud-bashdb-command-name "bashdb" "File name for executing Bashdb." :type 'string :group 'gud) ;; History of argument lists passed to bashdb. (defvar gud-bashdb-history nil) (defun gud-bashdb-massage-args (file args) (if xemacsp (cons (file-name-nondirectory file) args) args)) ;; There's no guarantee that Emacs will hand the filter the entire ;; marker at once; it could be broken up across several strings. We ;; might even receive a big chunk with several markers in it. If we ;; receive a chunk of text which looks like it might contain the ;; beginning of a marker, we save it here between calls to the ;; filter. (if xemacsp (defvar gud-bashdb-marker-acc "")) (defun gud-bashdb-marker-acc () (if xemacsp gud-bashdb-marker-acc gud-marker-acc)) (defun gud-bashdb-marker-acc-quote () (if xemacsp 'gud-bashdb-marker-acc 'gud-marker-acc)) (defun gud-bashdb-marker-filter (string) (save-match-data (set (gud-bashdb-marker-acc-quote) (concat (gud-bashdb-marker-acc) string)) (let ((output "")) ;; Process all the complete markers in this chunk. (while (string-match "^\\([^:\n]+\\):\\([0-9]+\\)[ *]*>.*\n" (gud-bashdb-marker-acc)) (setq ;; Extract the frame position from the marker. gud-last-frame (cons (substring (gud-bashdb-marker-acc) (match-beginning 1) (match-end 1)) (string-to-int (substring (gud-bashdb-marker-acc) (match-beginning 2) (match-end 2)))) ;; Append any text before the marker to the output we're going ;; to return - we don't include the marker in this text. output (concat output (substring (gud-bashdb-marker-acc) 0 (match-beginning 0)))) ;; Set the accumulator to the remaining text. (set (gud-bashdb-marker-acc-quote) (substring (gud-bashdb-marker-acc) (match-end 0)))) ;; Does the remaining text look like it might end with the ;; beginning of another marker? If it does, then keep it in ;; (gud-bashdb-marker-acc) until we receive the rest of it. Since we ;; know the full marker regexp above failed, it's pretty simple to ;; test for marker starts. (if (string-match "^\\([^:\n]+\\):\\([0-9]+\\)[ *]*>" (gud-bashdb-marker-acc)) (progn ;; Everything before the potential marker start can be output. (setq output (concat output (substring (gud-bashdb-marker-acc) 0 (match-beginning 0)))) ;; Everything after, we save, to combine with later input. (set (gud-bashdb-marker-acc-quote) (substring (gud-bashdb-marker-acc) (match-beginning 0)))) (setq output (concat output (gud-bashdb-marker-acc))) (set (gud-bashdb-marker-acc-quote) "")) output))) (defun gud-bashdb-find-file (f) (find-file-noselect f)) ;;;###autoload (defun bashdb (command-line) "Run bashdb on program FILE in buffer *gud-FILE*. The directory containing FILE becomes the initial working directory and source-file directory for your debugger." (interactive (if xemacsp (list (read-from-minibuffer "Run bashdb (like this): " (if (consp gud-bashdb-history) (car gud-bashdb-history) (format "%s " gud-bashdb-command-name)) nil nil '(gud-bashdb-history . 1))) (list (gud-query-cmdline 'bashdb)) )) (if xemacsp (progn (gud-overload-functions '((gud-massage-args . gud-bashdb-massage-args) (gud-marker-filter . gud-bashdb-marker-filter) (gud-find-file . gud-bashdb-find-file))) (gud-common-init command-line gud-bashdb-command-name)) (gud-common-init command-line 'gud-bashdb-massage-args 'gud-bashdb-marker-filter 'gud-bashdb-find-file) (set (make-local-variable 'gud-minor-mode) 'bashdb)) ;; Unsupported commands ;; condition foo set break condition to foo ;; condition clear break condition ;; display EXP evaluate and display EXP for each debug step ;; display show a list of display expressions ;; undisplay N remove display expression N ;; ! string passes string to a shell ;; quit quit (gud-def gud-break "break %l" "\C-b" "Set breakpoint at current line.") (gud-def gud-list-break "break" "b" "List breakpoints & break condition.") (gud-def gud-remove "delete %l" "\C-d" "Remove breakpoint at current line") (gud-def gud-remove-all "delete" "d" "Clear all breakpoints") (gud-def gud-cont "continue" "\C-r" "Continue with display.") (gud-def gud-next "next" "\C-n" "Step one line (skip functions).") (gud-def gud-print "print %e" "\C-p" "Evaluate bash expression at point.") (gud-def gud-help "help" "h" "Show all commands.") (gud-def gud-trace "trace" "t" "Toggle execution trace on/off") (setq comint-prompt-regexp "^bashdb> ") (setq paragraph-start comint-prompt-regexp) (run-hooks 'bashdb-mode-hook)) (provide 'bashdb) ;; bashdb.el ends here --- NEW FILE: PERMISSION --- >From mi...@or... Tue Aug 1 12:13:20 1995 Flags: 10 Return-Path: mi...@or... Received: from ruby.ora.com (ruby.ora.com [198.112.208.25]) by odin.INS.CWRU.Edu with ESMTP (8.6.12+cwru/CWRU-2.1-ins) id MAA01565; Tue, 1 Aug 1995 12:13:18 -0400 (from mi...@or... for <ch...@od...>) Received: (from fax@localhost) by ruby.ora.com (8.6.12/8.6.11) with UUCP id MAA23251; Tue, 1 Aug 1995 12:07:51 -0400 Received: by los.ora.com (4.1/Spike-2.1) id AA00672; Tue, 1 Aug 95 08:57:32 EDT Date: Tue, 1 Aug 95 08:57:32 EDT From: mi...@or... (Michael Loukides) Message-Id: <950...@lo...> Subject: Re: Ksh debugger from Rosenblatt's book [for bash] To: Chet Ramey <ch...@od...> Cc: cm...@or..., ca...@ii..., bro...@tm... In-Reply-To: Chet Ramey <ch...@od...>, Mon, 31 Jul 1995 16:22:48 -0400 I've modified a (modified) version of Bill Rosenblatt's ksh debugger to work with bash-2.0. Does ORA have any problem with me distributing it with bash-2.0? That's great! Go ahead and circulate it; in fact, we should probably grab it and stick it in our ftp archive, and put a reference to it in the book. (Too late to actually discuss the thing, at least for this edition). ------- |