1 #!/bin/bash
   2 #
   3 # /home/lantw44/.bash_include
   4 #
   5 # -- UTF-8 --
   6 #
   7 # 設定用外部檔案:
   8 #     (1) 若 .bash_title 存在且未設定自動修改視窗標題,則依照本檔案內定規則修改
   9 #     (2) 若 .bash_addps 存在,則第一行的的內容會加到 colorprompting 變數,第二
  10 #         行的內容會加到 nocolorprompting 變數
  11 
  12 #### if tty -s; then interactive_shell=1; fi
  13 if [[ "$-" == *i* ]] ; then interactive_shell=1; fi
  14 
  15 [ "$interactive_shell" ] && echo "Running .bash_include"
  16 [ "$interactive_shell" ] && default_tty_setting="`stty -g`"
  17 
  18 # Internal Variables
  19 
  20 colorprompting='\[\e[1;31m\]\!\[\e[m\] [\[\e[1;33m\]\u\[\e[m\]@\[\e[1;32m\]\h\[\e[m\] \[\e[1;36m\]\w\[\e[m\]]'
  21 nocolorprompting='\! [\u@\h \w]'
  22 
  23 if [ "$SSH_CONNECTION" ]
  24 then
  25     colorprompting="\[\e[1;44m\]*\[\e[m\]$colorprompting"
  26     nocolorprompting="*$nocolorprompting"
  27 fi
  28 
  29 if [ "$UNDER_JHBUILD" = "true" ]
  30 then
  31     colorprompting="$colorprompting[\[\e[1;35m\]JHBuild\[\e[m\]]"
  32     nocolorprompting="$nocolorprompting[JHBuild]"
  33 fi
  34 
  35 if [ -f "$HOME/.bash_addps" ]
  36 then
  37     exec 3< "$HOME/.bash_addps"
  38     read -u 3 -r oneline
  39     colorprompting="$oneline $colorprompting"
  40     read -u 3 -r oneline
  41     nocolorprompting="$oneline $nocolorprompting"
  42     exec 3<&-
  43     unset oneline
  44 fi
  45 
  46 if [ "$WINDOW" ]
  47 then
  48     colorprompting="$colorprompting<$WINDOW>"
  49     nocolorprompting="$nocolorprompting<$WINDOW>"
  50 fi
  51 
  52 if [ "$TMUX_PANE" ]
  53 then
  54     colorprompting="$colorprompting$TMUX_PANE"
  55     nocolorprompting="$nocolorprompting$TMUX_PANE"
  56 fi
  57 
  58 colorprompting="${colorprompting}\\$ "
  59 nocolorprompting="${nocolorprompting}\\$ "
  60 
  61 historycountfile="$HOME/.bash_history.count"
  62 historybackupfile="$HOME/.bash_history.bak"
  63 bgrunfiledir="$HOME/tmp/bgrun-`whoami`"
  64 trashdir="$HOME/trash"
  65 
  66 HISTSIZE=2147483647
  67 HISTFILESIZE=2147483647
  68 HISTCONTROL=ignoredups:ignorespace
  69 HISTTIMEFORMAT="%F %T "
  70 
  71 REALPATH_PROGRAM="realpath"
  72 
  73 CFLAGS="-Wall -pipe -g"
  74 
  75 
  76 # Environment Variables
  77 
  78 export EDITOR=vim
  79 export FCEDIT=vim
  80 export PAGER=less
  81 
  82 
  83 
  84 
  85 # Aliases
  86 
  87 alias startcolor='PS1=$colorprompting'
  88 alias stopcolor='PS1=$nocolorprompting'
  89 
  90 alias ll='ls -l'
  91 alias grep='grep --color=always'
  92 alias rm='rm -i'
  93 alias cp='cp -pi'
  94 alias mv='mv -i'
  95 alias jobs='jobs -l'
  96 alias less='less -RS'
  97 
  98 alias cccc='LANG=C;LANGUAGE=C;LC_ALL=C'
  99 alias enus='LANG=en_US.UTF-8;LANGUAGE=en_US:en;LC_ALL=en_US.UTF-8'
 100 alias big5='LANG=zh_TW.Big5;LANGUAGE=zh_TW:zh;LC_ALL=zh_TW.Big5'
 101 alias zhtw='LANG=zh_TW.UTF-8;LANGUAGE=zh_TW:zh;LC_ALL=zh_TW.UTF-8'
 102 
 103 alias savetty='default_tty_setting=`stty -g`'
 104 alias resetty='stty $default_tty_setting'
 105 
 106 alias vimhtml='vim -c "set ts=2" -c "set sw=2"'
 107 alias screen256='screen -T screen-256color'
 108 
 109 
 110 # Functions
 111 
 112 function compile_all ()
 113 {
 114     local noask=0
 115     local mycc="${CC}"
 116     local mycxx="${CPP}"
 117     [ "$1" = '' ] && echo "Which file(s) do you want to compile? " && return 1
 118     [ "$1" = "-n" ] && noask=1
 119     if [ "$noask" = "0" ]; then
 120         read -e -p "CFLAGS: " -i "$CFLAGS" NEWCFLAGS
 121         read -e -p "LDFLAGS: " -i "$LDFLAGS" NEWLDFLAGS
 122         [ "$NEWCFLAGS" '!=' '' ] && CFLAGS=$NEWCFLAGS
 123         [ "$NEWLDFLAGS" '!=' '' ] && LDFLAGS=$NEWLDFLAGS
 124     else
 125         shift
 126     fi
 127     [ -z "${mycc}" ] && mycc=cc
 128     [ -z "${mycxx}" ] && mycxx=c++
 129     while [ "$1" '!=' '' ]
 130     do
 131         local TARGETFILE="`echo "$1" | cut -d . -f 1`"
 132         local SUFFIX="`echo "$1" | cut -d . -f 2`"
 133         if [ -f "$1" ]; then
 134             true
 135         else
 136             printf\
 137             "\e[1;33mWarning\e[0m: $1 Non-existent file or not a regular file\n"
 138             shift ; continue
 139         fi
 140         [ "$TARGETFILE" = "$1" ] && shift && continue
 141         if [ "$SUFFIX" = "c" ]; then
 142             echo "[${mycc}] $1 -> $TARGETFILE"
 143             ${mycc} $CFLAGS "$1" $LDFLAGS -o "$TARGETFILE"
 144         elif [ "$SUFFIX" = "cpp" ]; then
 145             echo "[${mycxx}] $1 -> $TARGETFILE"
 146             ${mycxx} $CFLAGS "$1" $LDFLAGS -o "$TARGETFILE"
 147         else
 148             printf "$1: Unknown suffix (\e[1;33mskipped\e[0m)\n"
 149         fi
 150         [ "$?" '!=' "0" ] && printf\
 151             '\e[1;31mError\e[0m while compiling file\n'
 152         shift
 153     done
 154     return 0
 155 }
 156 
 157 
 158 function convert_to_html ()
 159 {
 160     while [ "$1" '!=' '' ]
 161     do
 162         for i in "$1"
 163         do
 164             vim $i -c 'set background=dark' \
 165                 -c 'highlight PreProc ctermfg=darkcyan' \
 166                 -c "$BEFORE_CONVERT_TO_HTML" \
 167                 -c "$BEFORE_CONVERT_TO_HTML1" \
 168                 -c "$BEFORE_CONVERT_TO_HTML2" \
 169                 -c TOhtml \
 170                 -c :w \
 171                 -c :qa
 172         done
 173         shift
 174     done
 175 }
 176 
 177 function mkscreenacl ()
 178 {
 179     PERMIT_COMMAND="select windowlist other meta detach reset hardcopy info redisplay lastmsg next prev xon xoff windows suspend help colon copy paste writebuf readbuf displays stuff attach"
 180     while [ "$1" '!=' '' ]
 181     do
 182         for i in $PERMIT_COMMAND
 183         do
 184             echo "aclchg $1 +x $i"
 185         done
 186         echo "aclchg $1 -rw \"\#?\""
 187         shift
 188     done
 189 }
 190 
 191 function get_file_size ()
 192 {
 193     split_arguments "$@"
 194     "${prefixlist[@]}" du -s "${arglist[@]}" | {
 195         read -d "   " dirsize
 196         echo "$dirsize"
 197         read throwaway
 198     }
 199     unset arglist
 200     unset prefixlist
 201 }
 202 
 203 ########## Background ##########
 204 
 205 alias bgr=bgrun
 206 alias bgv=bgview
 207 alias bgl=bglist
 208 alias bgc=bgcount
 209 alias bgls=bglist
 210 alias bgrm=bgclean
 211 
 212 function bgrun ()
 213 {
 214     [ "$#" = "0" ] && return 1
 215     [ '!' -d "$bgrunfiledir" ] && createdir_askmode "$bgrunfiledir" 0750
 216     local current_time=`date "+%Y%m%d-%H%M%S"`
 217     local cmdname=`echo "$1" | sed -e 's/-/_/g' -e 's/\\//_/g' -e 's/ /_/g'`
 218     if [ "`echo "$cmdname" | cut -c 1`" == "_" ]
 219     then
 220         cmdname=`echo "$cmdname" | cut -c 2-`
 221     fi
 222     local filename="$bgrunfiledir/$current_time-$cmdname"
 223     echo "Writing to $filename"
 224     {
 225         echo -n "$BASHPID " > "$filename"
 226         echo "$@" >> "$filename"
 227         exec "$@" &>> "$filename"
 228     } &
 229 }
 230 
 231 function bglist ()
 232 {
 233     local viewtime=0
 234     [ "$1" = "--full" ] && viewtime=1
 235     {
 236         for i in `find "$bgrunfiledir" -maxdepth 1 -mindepth 1 | sort`
 237         do
 238             [ "$viewtime" = "1" ] && echo "$i"
 239             head -n 1 "$i" | {
 240                 local procpid
 241                 local cmdline
 242                 read -d ' ' procpid
 243                 read cmdline
 244                 printf "(%5d) %s\n" "$procpid" "$cmdline"
 245             }
 246         done
 247     } | {
 248         if [ "$viewtime" = "1" ]
 249         then
 250             echo " INDEX         TIME          PID   COMMAND"
 251             local readstat=0
 252             local -i i=1
 253             while true
 254             do
 255                 local dateandtime_long
 256                 local cmdline
 257                 read dateandtime_long
 258                 read cmdline
 259                 [ "$?" '!=' "0" ] && break
 260                 local dateandtime=`basename "$dateandtime_long"`
 261     ####        local part_year=`echo $dateandtime | cut -c 1-4`
 262     ####        local part_month=`echo $dateandtime | cut -c 5-6`
 263     ####        local part_date=`echo $dateandtime | cut -c 7-8`
 264     ####        local part_hour=`echo $dateandtime | cut -c 10-11`
 265     ####        local part_minute=`echo $dateandtime | cut -c 12-13`
 266     ####        local part_second=`echo $dateandtime | cut -c 14-15`
 267                 echo "$dateandtime" | {
 268                     read -n 4 part_year
 269                     read -n 2 part_month
 270                     read -n 2 part_date
 271                     read -n 1 drop_this_char; unset drop_this_char
 272                     read -n 2 part_hour
 273                     read -n 2 part_minute
 274                     read -n 2 part_second
 275                     printf '%6d' "$i"
 276                     echo " $part_year-$part_month-$part_date $part_hour:$part_minute:$part_second $cmdline"
 277                 }
 278                 i=$i+1
 279             done
 280         else
 281             echo " INDEX    PID   COMMAND"
 282             cat -n
 283         fi
 284     } | $PAGER
 285 }
 286 
 287 function bgview ()
 288 {
 289     local -i yourchoice
 290     if [ "$1" = "" ]
 291     then
 292         yourchoice=`bgcount`
 293     else
 294         if [ "$1" -le "0" ]
 295         then
 296             yourchoice=$((`bgcount`+$1))
 297         else
 298             yourchoice=$1
 299         fi
 300     fi
 301     echo "Your choice is $yourchoice."
 302     local realfilename=`find "$bgrunfiledir" -maxdepth 1 -mindepth 1 | sort | sed -n ${yourchoice}p`
 303     head -n 1 "$realfilename" | {
 304         read -d ' ' procpid
 305         read cmdline
 306         echo "PID: $procpid"
 307         echo "Command Line: $cmdline"
 308     }
 309     read -e -p "View '$realfilename' ? " confirm
 310     if [ "$confirm" = "n" ] || [ "$confirm" = "N" ]
 311     then
 312         return 1
 313     fi
 314     {
 315         printf "===> Process Information: "
 316         cat "$realfilename"
 317     } | $PAGER
 318 }
 319 
 320 function bgcount ()
 321 {
 322     find "$bgrunfiledir" -maxdepth 1 -mindepth 1 | cut -d - -f 2,3 | wc | awk '{print $2}'
 323 }
 324 
 325 function bgclean ()
 326 {
 327     if [ "$1" = "all" ]
 328     then
 329         echo "Removing the directory $bgrunfiledir"
 330         rm -rf "$bgrunfiledir" &
 331         return 0
 332     else
 333         split_arguments "$@"
 334         local -i i=0
 335         while [ "${arglist[$i]}" ]
 336         do
 337             arglist[$i]="-e ${arglist[$i]}p"
 338             i=$i+1
 339         done
 340         local oneline
 341         find "$bgrunfiledir" -maxdepth 1 -mindepth 1 | sort | sed -n ${arglist[*]} | {
 342             while read oneline
 343             do
 344                 echo "Removing $oneline"
 345                 rm -f "$oneline"
 346             done
 347         }
 348     fi
 349     unset arglist
 350     unset prefixlist
 351 }
 352 
 353 function bgdu ()
 354 {
 355     local -i j=1
 356     {
 357         echo " INDEX     SIZE   PID   COMMAND"
 358         for i in `find "$bgrunfiledir" -maxdepth 1 -mindepth 1 | sort`
 359         do
 360             head -n 1 "$i" | {
 361                 local procpid
 362                 local cmdline
 363                 read -d ' ' procpid
 364                 read cmdline
 365                 printf "%6d %8d (%5d) %s\n" "$j" \
 366                     "`get_file_size "$i"`" \
 367                     "$procpid" "$cmdline"
 368             }
 369             j=$j+1
 370         done
 371     } | $PAGER
 372 }
 373 
 374 ########## Background End ##########
 375 
 376 function check_dmesg ()
 377 {
 378     [ "$#" = "0" ] && return 1
 379 
 380     while true
 381     do
 382         PREVIOS_DMESG_BUF="$DMESG_BUF"
 383         DMESG_BUF="`dmesg`"
 384         [ "$PREVIOS_DMESG_BUF" '!=' "$DMESG_BUF" ] && [ "$FIRST_RUN" = "0" ] && echo '===> You should check the system message buffer <==='
 385         sleep $1
 386         [ "$?" '!=' "0" ] && return 1
 387         FIRST_RUN=0
 388     done
 389 }
 390 
 391 function check_system_status ()
 392 {
 393     [ "$#" = "0" ] && return 1
 394 
 395     filename_mail="$MAIL"
 396     filename_messages="/var/log/messages"
 397     filename_audit="/var/log/audit/audit.log"
 398 
 399     while true
 400     do
 401         previous_dmesg_buf="$current_dmesg_buf"
 402         current_dmesg_buf="`dmesg`"
 403         previous_mail_info="$current_mail_info"
 404         current_mail_info="`ls -l "$filename_mail"`"
 405         previous_messages_info="$current_messages_info"
 406         current_messages_info="`ls -l "$filename_messages"`"
 407         previous_audit_info="$current_audit_info"
 408         current_audit_info="`ls -l "$filename_audit"`"
 409         if [ "$first_run" = "0" ]
 410         then
 411             [ "$previous_dmesg_buf" '!=' "$current_dmesg_buf" ] && echo "===> The system message buffer is modified (dmesg) <==="
 412             [ "$previous_mail_info" '!=' "$current_mail_info" ] && echo "===> Your mailbox $filename_mail is modified <==="
 413             [ "$previous_messages_info" '!=' "$current_messages_info" ] && echo "===> $filename_messages is modified <==="
 414             [ "$previous_audit_info" '!=' "$current_audit_info" ] && echo "===> $filename_audit is modified <==="
 415         fi
 416         sleep $1
 417         first_run=0
 418     done
 419 }
 420 
 421 function prehistory_backup ()
 422 {
 423     echo "Checking your current history file"
 424     local -i currentcount=`cat "$HISTFILE" | wc -l`
 425     [ '!' -f "$historycountfile" ] && touch "$historycountfile"
 426     local -i previoushistorycount
 427     previoushistorycount=`cat "$historycountfile"`
 428     if [ "$currentcount" -lt "$previoushistorycount" ]
 429     then
 430         printf "\e[1;31mWarning\e[m: Your $HISTFILE may be TRUNCATED OR OVERWRITTEN BY OTHER PROGRAMS!\n"
 431         printf "Note: \e[1;33m$currentcount\e[m < $previoushistorycount\n"
 432         echo "Your $historycountfile and $historybackupfile will not be overwritten until this problem is fixed."
 433         echo " 1. Check your $HISTFILE."
 434         echo " 2. Edit your $HISTFILE manually if some unexpected changes are found."
 435         echo "    (You may need $historybackupfile to do it) "
 436         echo " 3. Remove the file $historycountfile."
 437         echo " 4. Run the command \`prehistory_backup' again."
 438         return 3
 439     fi
 440     echo -n "Backing up your current history file ($previoushistorycount -> $currentcount, "
 441     if [ "$previoushistorycount" = "$currentcount" ]
 442     then
 443         echo "no modification)"
 444     else
 445         echo "+$(($currentcount-$previoushistorycount)))"
 446     fi
 447     echo "$currentcount" > "$historycountfile"
 448     \cp -f "$HISTFILE" "$historybackupfile"
 449 }
 450 
 451 ########## Trash Manager ##########
 452 
 453 alias trash_put=trash_mv
 454 alias trash_add=trash_mv
 455 alias trash_list=trash_ls
 456 alias trash_ct=trash_count
 457 alias trash_restore=trash_recover
 458 alias trash_rc=trash_recover
 459 alias trash_drop=trash_rm
 460 alias trash_clean=trash_rm
 461 
 462 function trash_mv ()
 463 {
 464     [ "$#" = "0" ] && return 1
 465     [ '!' -d "$trashdir" ] && createdir_askmode "$trashdir" 0700
 466     local original_path
 467     local current_time
 468     local -i i=0
 469     split_arguments "$@"
 470     while [ "${arglist[$i]}" ]
 471     do
 472         original_path="`"${prefixlist[@]}" $REALPATH_PROGRAM "${arglist[$i]}"`"
 473         current_time=`date "+%Y%m%d-%H%M%S"`
 474         better_time=`date "+%Y-%m-%d %H:%M:%S"`
 475         dirname="`basename "${arglist[$i]}" | sed -e 's/-/_/g' -e 's/ /_/g'`"
 476         fulldirname="$trashdir/$current_time-$dirname"
 477         mkdir -p "$fulldirname"
 478         echo "Move: ${arglist[$i]} -> $fulldirname"
 479         "${prefixlist[@]}" mv "${arglist[$i]}" "$fulldirname"
 480         if [ "$?" = "0" ]
 481         then
 482             echo "$better_time" > "$fulldirname/information.date"
 483             echo "$original_path" > "$fulldirname/information.path"
 484         else
 485             rmdir "$fulldirname"
 486         fi
 487         i=$i+1
 488         shift
 489     done
 490     unset arglist
 491     unset prefixlist
 492 }
 493 
 494 function trash_rm ()
 495 {
 496     split_arguments "$@"
 497     local -i i=0
 498     while [ "${arglist[$i]}" ]
 499     do
 500         arglist[$i]="-e ${arglist[$i]}p"
 501         i=$i+1
 502     done
 503     trash_dirname=`find "$trashdir" -mindepth 1 -maxdepth 1 | sort | sed -n ${arglist[*]} `
 504     echo 'Type rm -rf $trash_dirname to remove them.'
 505     unset arglist
 506     unset prefixlist
 507 }
 508 
 509 function trash_ls ()
 510 {
 511     local -i i=1
 512     local oneline
 513     find "$trashdir" -mindepth 1 -maxdepth 1 | sort | {
 514         while read oneline
 515         do
 516             printf "%6d %s %s\n" "$i" \
 517                 "`cat "$oneline/information.date"`" \
 518                 "`cat "$oneline/information.path"`"
 519             i=$i+1
 520         done
 521     } | $PAGER
 522 }
 523 
 524 function trash_pushd ()
 525 {
 526     [ -z "$1" ] && return 1
 527     pushd `find "$trashdir" -mindepth 1 -maxdepth 1 | sort | sed -n $1p`
 528 }
 529 
 530 function trash_cd ()
 531 {
 532     [ -z "$1" ] && return 1
 533     cd `find "$trashdir" -mindepth 1 -maxdepth 1 | sort | sed -n $1p`
 534 }
 535 
 536 function trash_recover ()
 537 {
 538     [ -z "$1" ] && return 1
 539     split_arguments "$@"
 540     local -i i=0
 541     while [ "${arglist[$i]}" ]
 542     do
 543         arglist[$i]="-e ${arglist[$i]}p"
 544         i=$i+1
 545     done
 546     find "$trashdir" -mindepth 1 -maxdepth 1 | sort | sed -n ${arglist[*]} | {
 547         while read oneline
 548         do
 549             local fromfile="$oneline/`basename "$(cat "$oneline/information.path")"`"
 550             local tofile="`dirname "$(cat "$oneline/information.path")"`"
 551             if [ -e "`cat "$oneline/information.path"`" ]
 552             then
 553                 echo "Destination file exists."
 554                 continue
 555             fi
 556             echo "Move: $fromfile -> $tofile"
 557             "${prefixlist[@]}" mv -f "$fromfile" "$tofile"
 558             if [ "$?" = "0" ]
 559             then
 560                 echo "Remove: $oneline"
 561                 \rm -rf "$oneline"
 562             fi
 563         done
 564     }
 565     unset arglist
 566     unset prefixlist
 567 }
 568 
 569 function trash_count ()
 570 {
 571     find "$trashdir" -mindepth 1 -maxdepth 1 | wc | awk '{print $2}'
 572 }
 573 
 574 function trash_du ()
 575 {
 576     split_arguments "$@"
 577     local oneline
 578     local -i i=1
 579     find "$trashdir" -maxdepth 1 -mindepth 1 | sort | {
 580         while read oneline
 581         do
 582             printf "%6d %8d %s\n" "$i" \
 583                 "`get_file_size "$oneline" -- "${prefixlist[@]}"`" \
 584                 "`cat "$oneline/information.path"`"
 585             i=$i+1
 586         done
 587     } | $PAGER
 588     unset arglist
 589     unset prefixlist
 590 }
 591 
 592 ########## Trash Manager End ##########
 593 
 594 function split_arguments ()
 595 {
 596     local argcount=$#
 597     local -i i=0
 598     local prefix_start=0
 599     while [ "$1" ]
 600     do
 601         if [ "$prefix_start" == "0" ]
 602         then
 603             if [ "$1" = "--" ]
 604             then
 605                 prefix_start=1
 606                 i=0
 607                 shift
 608                 continue
 609             else
 610                 arglist[$i]="$1"
 611             fi
 612         else
 613             prefixlist[$i]="$1"
 614         fi
 615         i=$i+1
 616         shift
 617     done
 618 }
 619 
 620 function check_important_files ()
 621 {
 622     IMPORTANT_FILES="$HOME/.screenrc $HOME/.vimrc"
 623     for i in $IMPORTANT_FILES
 624     do
 625         [ '!' -f "$i" ] && printf "\e[1;31mWarning\e[m: \e[1;33m$i\e[m does not exist.\n"
 626     done
 627 }
 628 
 629 ########## PATH Editor ##########
 630 
 631 function split_path_core ()
 632 {
 633     echo "$current_path" | {
 634         while read -d : oneline
 635         do
 636             [ '!' "$oneline" = '^' ] && echo "$oneline"
 637         done
 638         [ '!' "$oneline" = '^' ] && echo "$oneline"
 639     }
 640     unset oneline
 641 }
 642 
 643 function split_path ()
 644 {
 645     coproc split_path_core
 646     readarray -t -u ${COPROC[0]} patharr
 647     wait $COPROC_PID
 648 }
 649 
 650 function update_path ()
 651 {
 652     current_path=''
 653     local -i i=0
 654     local firsttime="yes"
 655     while [ "${patharr[$i]}" ]
 656     do
 657         if [ '!' "${patharr[$i]}" = "^" ]
 658         then
 659             if [ "$firsttime" ]
 660             then
 661                 firsttime=''
 662             else
 663                 current_path+=':'
 664             fi
 665             current_path+="${patharr[$i]}"
 666         fi
 667         i=$i+1
 668     done
 669 }
 670 
 671 function old_path_editor ()
 672 {
 673     old_path_editor_core
 674 }
 675 
 676 function old_ldpath_editor ()
 677 {
 678     old_path_editor_core ld
 679 }
 680 
 681 function old_path_editor_core ()
 682 {
 683     if [ "$1" = "ld" ]
 684     then
 685         export current_path="$LD_LIBRARY_PATH"
 686     else
 687         export current_path="$PATH"
 688     fi
 689     local should_continue="yes"
 690     local command
 691     local command_sub
 692     local command_sub2
 693     local -i i
 694     while [ "$should_continue" ]
 695     do
 696         split_path
 697         i=0
 698         echo "========================================"
 699         while [ "${patharr[$i]}" ]
 700         do
 701             echo "$i: ${patharr[$i]}"
 702             i=$i+1
 703         done
 704         [ "$i" = '0' ] && echo "(Empty or not declared)"
 705         echo "========================================"
 706         read -e -p "[A]ppend/(D)elete/(E)dit/(M)ove/(R)eset/(Q)uit ? " command
 707         case "$command" in
 708             ''|A|a)
 709                 read -e -p "Type a new entry: " patharr[$i]
 710                 update_path
 711                 ;;
 712             D|d)
 713                 read -e -p "Index: " command_sub
 714                 patharr[$command_sub]='^'
 715                 update_path
 716                 ;;
 717             E|e)
 718                 read -e -p "Index: " command_sub
 719                 read -e -p "Modify this entry: " -i "${patharr[$command_sub]}" patharr[$command_sub]
 720                 update_path
 721                 ;;
 722             M|m)
 723                 read -e -p "From: " command_sub
 724                 read -e -p "To: " command_sub2
 725                 swaptmp="${patharr[$command_sub]}"
 726                 patharr[$command_sub]="${patharr[$command_sub2]}"
 727                 patharr[$command_sub2]="$swaptmp"
 728                 unset swaptmp
 729                 update_path
 730                 ;;
 731             R|r)
 732                 if [ "$1" = "ld" ]
 733                 then
 734                     current_path="$LD_LIBRARY_PATH"
 735                 else
 736                     current_path="$PATH"
 737                 fi
 738                 ;;
 739             Q|q)
 740                 if [ "$1" = "ld" ]
 741                 then
 742                     export LD_LIBRARY_PATH="$current_path"
 743                     echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
 744                     history -s "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
 745                 else
 746                     export PATH="$current_path"
 747                     echo "PATH=$PATH"
 748                     history -s "PATH=$PATH"
 749                 fi
 750                 should_continue=''
 751                 ;;
 752             *)
 753                 printf " \e[33m*** Unknown command ***\e[m \n"
 754                 ;;
 755         esac
 756     done
 757     unset patharr
 758     unset current_path
 759 }
 760 
 761 ########## PATH Editor End ##########
 762 
 763 ########## New PATH Editor ##########
 764 
 765 function ldpath_editor ()
 766 {
 767     path_editor LD_LIBRARY_PATH
 768 }
 769 
 770 function newpath_init ()
 771 {
 772     unset newpath
 773     local pathsp="$pathorgval"
 774     local pathentry
 775     local -i i
 776     eval pathsp='"${pathsp// /\\}"'
 777     pathsp="${pathsp//:/ }"
 778     i=0
 779     for pathentry in $pathsp
 780     do
 781         newpath[$i]="${pathentry//\\/ }"
 782         i=$i+1
 783     done
 784 }
 785 
 786 function newpath_gen ()
 787 {
 788     local -i i
 789     pathmodval=""
 790     i=0
 791     while [ "${newpath[$i]}" ]
 792     do
 793         if [ "$i" != 0 ]; then pathmodval+=":"; fi
 794         pathmodval+="${newpath[$i]}"
 795         i=$i+1
 796     done
 797 }
 798 
 799 function path_editor ()
 800 {
 801     local newpathvarname
 802     local badcommand
 803     local command
 804     local command_sub
 805     local command_sub2
 806     local should_continue="yes"
 807     local -i i
 808 
 809     if [ -z "$1" ]
 810     then
 811         newpathvarname="PATH"
 812     else
 813         newpathvarname="$1"
 814     fi
 815 
 816     eval pathorgval=\${${newpathvarname}}
 817     newpath_init
 818 
 819     while [ "$should_continue" ]
 820     do
 821         i=0
 822         echo -n $'\e[2J\e[0;0H'
 823         if [ "$badcommand" = "yes" ]; then
 824             printf " \e[33m*** Command \`$command' is unknown ***\e[m \n"
 825             badcommand=""
 826         fi
 827         echo "        New PATH Editor for BASH        "
 828         echo "========================================"
 829         echo "Environment Variable: $newpathvarname"
 830         echo "----------------------------------------"
 831         while [ "${newpath[$i]}" ]
 832         do
 833             echo "$i: ${newpath[$i]}"
 834             i=$i+1
 835         done
 836         [ "$i" = '0' ] && echo "(Empty or not declared)"
 837         echo "========================================"
 838         read -e -p "[A]ppend/(I)nsert/(D)elete/(E)dit/(M)ove/(S)wap/(R)eset/(Q)uit ? " command
 839         case "$command" in
 840             ''|A|a)
 841                 read -e -p "Type a new entry: " newpath[$i]
 842                 ;;
 843             I|i)
 844                 read -e -p "Type a new entry: " command_sub
 845                 if [ -z "$command_sub" ]; then continue; fi
 846                 newpath_tmp=( "${newpath[@]}" )
 847                 unset newpath
 848                 newpath="$command_sub"
 849                 i=0
 850                 while [ "${newpath_tmp[$i]}" ]
 851                 do
 852                     newpath[$i+1]="${newpath_tmp[$i]}"
 853                     i=$i+1
 854                 done
 855                 unset newpath_tmp
 856                 ;;
 857             D|d)
 858                 read -e -p "Index: " command_sub
 859                 if [ -z "$command_sub" ]; then continue; fi
 860                 i="$command_sub"
 861                 i=$i+1
 862                 while [ "${newpath[$i]}" ]
 863                 do
 864                     newpath[$i-1]="${newpath[$i]}"
 865                     i=$i+1
 866                 done
 867                 unset newpath[$i-1]
 868                 ;;
 869             E|e)
 870                 read -e -p "Index: " command_sub
 871                 read -e -p "Modify this entry: " -i "${newpath[$command_sub]}" newpath[$command_sub]
 872                 ;;
 873             M|m)
 874                 read -e -p "From: " command_sub
 875                 read -e -p "To: " command_sub2
 876                 if [ "$command_sub" -eq "$command_sub2" ]; then continue; fi
 877                 cmdsubval="${newpath[$command_sub]}"
 878                 if [ "$command_sub" -gt "$command_sub2" ]; then
 879                     i="$command_sub"
 880                     while [ "$i" -gt "$command_sub2" ]
 881                     do
 882                         newpath[$i]="${newpath[$i-1]}"
 883                         i=$i-1
 884                     done
 885                     newpath[$command_sub2]="$cmdsubval"
 886                 else
 887                     i="$command_sub"
 888                     while [ "$i" -lt "$command_sub2" ]
 889                     do
 890                         newpath[$i]="${newpath[$i+1]}"
 891                         i=$i+1
 892                     done
 893                     newpath[$command_sub2]="$cmdsubval"
 894                 fi
 895                 unset cmdsubval
 896                 ;;
 897             S|s)
 898                 read -e -p "First entry: " command_sub
 899                 read -e -p "Second entry: " command_sub2
 900                 swaptmp="${newpath[$command_sub]}"
 901                 newpath[$command_sub]="${newpath[$command_sub2]}"
 902                 newpath[$command_sub2]="$swaptmp"
 903                 unset swaptmp
 904                 ;;
 905             R|r)
 906                 read -e -p "Discard all changes [y/N] ? " command_sub
 907                 if [ "$command_sub" = "y" ]; then
 908                     eval pathorgval=\${${newpathvarname}}
 909                     newpath_init
 910                 fi
 911                 ;;
 912             Q|q)
 913                 newpath_gen
 914                 eval export ${newpathvarname}=\"$pathmodval\"
 915                 echo "${newpathvarname}=$pathmodval"
 916                 history -s "${newpathvarname}=$pathmodval"
 917                 should_continue=''
 918                 ;;
 919             *)
 920                 badcommand="yes"
 921                 ;;
 922         esac
 923     done
 924     unset newpath
 925     unset pathorgval
 926     unset pathmodval
 927 }
 928 
 929 ########## New PATH Editor End ##########
 930 
 931 ########## Configuration File ##########
 932 
 933 function configfile_fetch ()
 934 {
 935     local mirror_list="
 936         http://www.tfcis.org/~lantw44/configfile/
 937         http://phantom.tfcis.org/~lantw44/mirror/forum_tfcis_org/configfile/
 938         http://master.lant.com.tw/~lantw44/configfile/
 939         http://www.csie.ntu.edu.tw/~b01902062/configfile/"
 940     local url_append
 941     local file_name
 942     local file_version
 943 
 944     if [ "$3" ]; then
 945         url_append="$3"
 946     else
 947         url_append="Unix-like/"
 948     fi
 949     if [ "$1" ]; then
 950         file_name="$1"
 951     else
 952         file_name="bash_include vimrc screenrc"
 953     fi
 954     if [ "$2" ]; then
 955         file_version="-$2"
 956     else
 957         url_append="${url_append}latest/"
 958     fi
 959 
 960     for file in $file_name
 961     do
 962         for site in $mirror_list
 963         do
 964             if fetch_remote_file "$HOME/.${file}.new" \
 965                 "${site}${url_append}${file}${file_version}"
 966             then
 967                 [ -e "$HOME/.${file}" ] && \
 968                     mv -vf "$HOME/.${file}" "$HOME/.${file}.old"
 969                 mv -vf "$HOME/.${file}.new" "$HOME/.${file}"
 970                 break
 971             fi
 972         done
 973     done
 974 }
 975 
 976 function configfile_initial_setup ()
 977 {
 978     cat >> ~/.bashrc << EOF
 979 if [ -f ~/.bash_include ]; then
 980     . ~/.bash_include
 981 fi
 982 EOF
 983     if [ "`uname`" = "FreeBSD" ]; then
 984         cat >> ~/.bash_login << EOF
 985 GET_TTY_NAME=`tty | cut -c 9`
 986 [ "$GET_TTY_NAME" = 'v' ] && echo "Login from local virtual terminal: `tty`"
 987 [ "$GET_TTY_NAME" = 'p' ] && echo "Login from pseudo terminal: `tty`"
 988 [ "$GET_TTY_NAME" = '/' ] && echo "Login from pseudo terminal: `tty`"
 989 unset GET_TTY_NAME
 990 EOF
 991     fi
 992     cat >> ~/.bash_login << EOF
 993 if [ -f ~/.bash_include ]; then
 994     . ~/.bashrc
 995 fi
 996 EOF
 997 }
 998 
 999 function fetch_remote_file ()
1000 {
1001     local rval
1002     printf "==> Fetch remote file \e[1;33m$2\e[m as \e[1;35m$1\e[m ...\n"
1003     if check_command_existent curl; then
1004         curl -f -o "$1" "$2"
1005         rval=$?
1006     elif check_command_existent fetch; then
1007         fetch -o "$1" "$2"
1008         rval=$?
1009     elif check_command_existent wget; then
1010         wget --progress=dot -O "$1" "$2"
1011         rval=$?
1012     else
1013         echo "<== Sorry, I don't know how to fetch remote files on your system"
1014         return 1
1015     fi
1016     if [ "$rval" = "0" ]; then
1017         printf "<== \e[1;32mDone\e[m\n"
1018     else
1019         printf "<== \e[1;31mFailed\e[m\n"
1020     fi
1021     return $rval
1022 }
1023 
1024 ########## Configuration File End  ##########
1025 
1026 function varset ()
1027 {
1028     local varoldvalue
1029     local varnewvalue
1030     while [ "$1" ]
1031     do
1032         eval varoldvalue=\${$1}
1033         read -r -e -p "$1=" -i "$varoldvalue" varnewvalue
1034         eval $1=\"$varnewvalue\"
1035         shift
1036     done
1037 }
1038 
1039 function is_file_type ()
1040 {
1041     local filename="$1"
1042     local typename="$2"
1043     shift 2
1044     [ "`"$@" find "$filename" -maxdepth 0 -type "$typename"`" ] && return 0
1045     return 1
1046 }
1047 
1048 function editlink ()
1049 {
1050     local newdest
1051     local orgdest
1052     split_arguments "$@"
1053     local -i i=0
1054     while [ "${arglist[$i]}" ]
1055     do
1056         if is_file_type "${arglist[$i]}" "l" "${prefixlist[@]}"; then
1057             orgdest="`${prefixlist[@]} readlink "${arglist[$i]}"`"
1058             read -e -p "EditLink: ${arglist[$i]} -> " -i "$orgdest" newdest
1059         else
1060             printf "\e[1;33mWarning\e[m: ${arglist[$i]} is not a symbolic link.\n"
1061             i=$i+1
1062             continue
1063         fi
1064         if [ "$newdest" ] && [ "$newdest" '!=' "$orgdest" ]; then
1065             "${prefixlist[@]}" rm -f "${arglist[$i]}"
1066             "${prefixlist[@]}" ln -sv "$newdest" "${arglist[$i]}"
1067         fi
1068         i=$i+1
1069     done
1070     unset arglist
1071     unset prefixlist
1072 }
1073 
1074 function backup_file ()
1075 {
1076     split_arguments "$@"
1077     local current_time=`date +%Y%m%d`
1078     local rootfilename
1079     local -i i=0
1080     local -i j
1081     while [ "${arglist[$i]}" ]
1082     do
1083         if [ '!' -f "${arglist[$i]}" ]
1084         then
1085             printf "\e[1;31mError\e[m: ${arglist[$i]} does not exist or it is not a regular file.\n"
1086             i=$i+1
1087             continue
1088         fi
1089         rootfilename="${arglist[$i]}.$current_time"
1090         if [ -e "$rootfilename" ]
1091         then
1092             j=0
1093             while [ "$j" -lt "10" ]
1094             do
1095                 if [ -e "$rootfilename.$j" ]
1096                 then
1097                     j=$j+1
1098                     continue
1099                 else
1100                     "${prefixlist[@]}" \cp -p "${arglist[$i]}" "$rootfilename.$j"
1101                     history -s "${prefixlist[@]}" \cp -p "${arglist[$i]}" "$rootfilename.$j"
1102                     "${prefixlist[@]}" touch -r "${arglist[$i]}" "$rootfilename.$j"
1103                     history -s "${prefixlist[@]}" touch -r "${arglist[$i]}" "$rootfilename.$j"
1104                     break
1105                 fi
1106             done
1107             if [ '!' "$j" -lt "10" ]
1108             then
1109                 printf "\e[1;31mError\e[m: Can not create a backup file for ${arglist[$i]}.\n"
1110                 printf "\e[1;33mPlease delete some backup file because I only use 0 - 9.\e[m\n"
1111             fi
1112         else
1113             "${prefixlist[@]}" \cp -p "${arglist[$i]}" "$rootfilename"
1114             history -s "${prefixlist[@]}" \cp -p "${arglist[$i]}" "$rootfilename"
1115             "${prefixlist[@]}" touch -r "${arglist[$i]}" "$rootfilename"
1116             history -s "${prefixlist[@]}" touch -r "${arglist[$i]}" "$rootfilename"
1117         fi
1118         i=$i+1
1119     done
1120     unset arglist
1121     unset prefixlist
1122 }
1123 
1124 function keep_sudo_credential ()
1125 {
1126     if [ "$1" ]
1127     then
1128         update_sudo_interval="$1"
1129     else
1130         update_sudo_interval="280"
1131     fi
1132     while true
1133     do
1134         sudo -v
1135         sleep "$update_sudo_interval"
1136     done
1137 }
1138 
1139 function get_memory_info ()
1140 {
1141     case "`uname`" in
1142         "Linux"|"GNU")
1143             local meminfoline="`free -m | \grep -i mem`"
1144             local swapinfoline="`free -m | \grep -i swap`"
1145             local memtotal="`echo "$meminfoline" | awk '{print $2}'`"
1146             local memused="`echo "$meminfoline" | awk '{print $3}'`"
1147             local membuf="`echo "$meminfoline" | awk '{print $6}'`"
1148             local memcache="`echo "$meminfoline" | awk '{print $7}'`"
1149             local memprog=$(($memused-$membuf-$memcache))
1150             local swaptotal="`echo "$swapinfoline" | awk '{print $2}'`"
1151             local swapused="`echo "$swapinfoline" | awk '{print $3}'`"
1152             echo "Memory: $memused / $memtotal MB (`printf %2d $(($memused*100/$memtotal))`%)"
1153             echo "Detail:"
1154             echo "    Used:    `printf %5d $memprog` MB (`printf %2d $(($memprog*100/$memtotal))`%)"
1155             echo "    Buffers: `printf %5d $membuf` MB (`printf %2d $(($membuf*100/$memtotal))`%)"
1156             echo "    Cached:  `printf %5d $memcache` MB (`printf %2d $(($memcache*100/$memtotal))`%)"
1157             if [ "$swaptotal" = "0" ]
1158             then
1159                 echo "Swap: not available"
1160             else
1161                 echo "Swap: $swapused / $swaptotal MB (`printf %2d $(($swapused*100/$swaptotal))`%)"
1162             fi
1163             ;;
1164         "FreeBSD")
1165             local mempagesize="`sysctl -n hw.pagesize`"
1166             local mempagecount="`sysctl -n hw.availpages`"
1167             local memactive="`sysctl -n vm.stats.vm.v_active_count`"
1168             local meminactive="`sysctl -n vm.stats.vm.v_inactive_count`"
1169             local memwire="`sysctl -n vm.stats.vm.v_wire_count`"
1170             local memcache="`sysctl -n vm.stats.vm.v_cache_count`"
1171             local memfree="`sysctl -n vm.stats.vm.v_free_count`"
1172             local swapenabled="`sysctl -n vm.swap_enabled`"
1173             echo "Memory (Active):   `printf %5d $(($memactive*$mempagesize/1048576))` MB (`printf %2d $(($memactive*100/$mempagecount))`%)"
1174             echo "Memory (Inactive): `printf %5d $(($meminactive*$mempagesize/1048576))` MB (`printf %2d $(($meminactive*100/$mempagecount))`%)"
1175             echo "Memory (Wired):    `printf %5d $(($memwire*$mempagesize/1048576))` MB (`printf %2d $(($memwire*100/$mempagecount))`%)"
1176             echo "Memory (Cache):    `printf %5d $(($memcache*$mempagesize/1048576))` MB (`printf %2d $(($memcache*100/$mempagecount))`%)"
1177             echo "Memory (Free):     `printf %5d $(($memfree*$mempagesize/1048576))` MB (`printf %2d $(($memfree*100/$mempagecount))`%)"
1178             echo "Total Memory:      `printf %5d $(($mempagecount*$mempagesize/1048576))` MB"
1179             if [ "$swapenabled" = "1" ]; then
1180                 echo ""
1181                 echo "Swap devices:"
1182                 swapinfo -m
1183             else
1184                 echo "Swap: not enabled"
1185             fi
1186             ;;
1187         *)
1188             echo "Unsupported operating system."
1189             ;;
1190     esac
1191 }
1192 
1193 function set_console_title ()
1194 {
1195     case "$TERM" in
1196         screen*)
1197             printf "\033]0;"
1198             echo -n "$*"
1199             printf "\033\\"
1200             ;;
1201         xterm*)
1202             printf "\033]0;"
1203             echo -n "$*"
1204             printf "\007"
1205             ;;
1206         *)
1207             echo "Your terminal may not have the hardstatus line."
1208             echo "Note: TERM=$TERM"
1209             ;;
1210     esac
1211 }
1212 
1213 function mvfile ()
1214 {
1215     local nocheck=0
1216     [ "$1" = "-n" ] && nocheck=1 && shift
1217     split_arguments "$@"
1218     local -i i=0
1219     while [ "${arglist[$i]}" ]
1220     do
1221         if [ "$nocheck" = "0" ] && [ '!' -e "${arglist[$i]}" ]
1222         then
1223             printf "\e[33mWarning\e[m: ${arglist[$i]} does not exist. (Use -n to override)\n"
1224             i=$i+1
1225             continue
1226         fi
1227         echo "Old name: ${arglist[$i]}"
1228         read -p "New name: " -e -i "${arglist[$i]}" new_file_name
1229         if [ "$new_file_name" ] && [ "${arglist[$i]}" != "$new_file_name" ]
1230         then
1231             "${prefixlist[@]}" mv -iv "${arglist[$i]}" "$new_file_name"
1232             history -s "${prefixlist[@]}" mv -iv "${arglist[$i]}" "$new_file_name"
1233         fi
1234         i=$i+1
1235     done
1236     unset arglist
1237     unset prefixlist
1238     unset new_file_name
1239 }
1240 
1241 function createdir_askmode ()
1242 {
1243     newdir_mode="$2"
1244     if mkdir -p "$1"
1245     then
1246         echo "Directory $1 is created."
1247         printf "Change the mode of the directory... "
1248         read -i "$newdir_mode" -p ">>> Mode: " -e newdir_mode
1249         chmod "$newdir_mode" "$1"
1250     else
1251         echo "Cannot create directory $1!"
1252         return 1
1253     fi
1254 }
1255 
1256 function get_terminal_size ()
1257 {
1258     # ESC 7              = 儲存游標位置和屬性
1259     # ESC [r             = 啟用全螢幕捲動
1260     # ESC [{row};{col}H  = 移動游標
1261     # ESC 6n             = 回報目前游標位置
1262     # ESC 8              = 還原游標位置和屬性
1263     echo -n $'\e7\e[r\e[999;999H\e[6n\e8' 1>&2
1264     read -s -d R getsize
1265     echo $getsize | sed 's#..\([0-9]*\);\([0-9]*\)#LINES=\1 COLUMNS=\2#'
1266 }
1267 
1268 function set_terminal_size ()
1269 {
1270     eval "export `get_terminal_size`"
1271     stty cols $COLUMNS rows $LINES
1272 }
1273 
1274 function unzip_nomac ()
1275 {
1276     unzip "$@" -x '__MACOSX/*' '*.DS_Store'
1277     return $?
1278 }
1279 
1280 function gen_ms_inet_shortcut () {
1281     [ "$#" != "2" ] && {
1282         echo "Usage: $FUNCNAME filename url"
1283     } && return 1
1284 
1285     {
1286         echo "[InternetShortcut]"
1287         echo "URL=$2"
1288     } > "$1"
1289 }
1290 
1291 function check_command_existent ()
1292 {
1293     which "$1" &> /dev/null
1294     return $?
1295 }
1296 
1297 function rpmdu () {
1298     local div_base=1
1299     local div_name="KB"
1300     local total=0
1301     if [ "`echo "$1" | cut -c 1`" = "-" ]
1302     then
1303         local optname=`echo "$1" | cut -c 2-`
1304         case "$optname" in
1305             "k")
1306                 ;;
1307             "m")
1308                 div_base=1024
1309                 div_name=MB
1310                 ;;
1311             "g")
1312                 div_base=1048576
1313                 div_name=GB
1314                 ;;
1315             *)
1316                 echo "Usage: $FUNCNAME [OPTION] package_name..."
1317                 echo "    -k KB"
1318                 echo "    -m MB"
1319                 echo "    -g GB"
1320                 return 1
1321                 ;;
1322         esac
1323         shift
1324     fi
1325 
1326     while [ "$1" ]
1327     do
1328         rpm -ql "$1" | {
1329             while read oneline
1330             do
1331                 if [ -f "$oneline" ]
1332                 then
1333                     du -k "$oneline"
1334                 fi
1335             done
1336         } | {
1337             while read -d $'\t' filesize
1338             do
1339                 total=$((${total}+${filesize}))
1340                 read
1341             done
1342             printf "%9d %s %s\n" "$(($total/$div_base))" "$div_name" "$1"
1343         }
1344 
1345         shift
1346     done
1347 }
1348 
1349 function rpmsize () {
1350     local div_base=1
1351     local div_name="Bytes"
1352     local total=0
1353     local filesize
1354     if [ "`echo "$1" | cut -c 1`" = "-" ]
1355     then
1356         optname=`echo "$1" | cut -c 2-`
1357         case "$optname" in
1358             "b")
1359                 ;;
1360             "k")
1361                 div_base=1024
1362                 div_name=KB
1363                 ;;
1364             "m")
1365                 div_base=1048576
1366                 div_name=MB
1367                 ;;
1368             "g")
1369                 div_base=1073741824
1370                 div_name=GB
1371                 ;;
1372             *)
1373                 echo "Usage: $FUNCNAME [OPTION] package_name..."
1374                 echo "    -b Byte"
1375                 echo "    -k KB"
1376                 echo "    -m MB"
1377                 echo "    -g GB"
1378                 return 1
1379                 ;;
1380         esac
1381         shift
1382     fi
1383     while [ "$1" ]
1384     do
1385         total=0
1386         filesize=`rpm -q "$1" --queryformat "%{SIZE} "`
1387         for i in $filesize
1388         do
1389             total=$((${total}+${i}))
1390         done
1391         printf "%12d %s %s\n" "$(($total/$div_base))" "$div_name" "$1"
1392         shift
1393     done
1394 }
1395 
1396 function freebsd_ports_should_rebuild () {
1397     reqcomp=$(ldd -f '%a %o %p\n' /usr/local/bin/* /usr/local/sbin/* \
1398         2>/dev/null | grep 'not found' | \
1399         { while read oneline; do echo ${oneline} | cut -d ' ' -f 1; done; } | uniq)
1400     reqpkg=$({ for i in $reqcomp; do pkg_info -q -W $i; done } | sort | uniq)
1401     echo $reqpkg
1402 }
1403 
1404 ########## Help ##########
1405 
1406 alias helpf='help_function'
1407 alias helpm='help_myself'
1408 
1409 function print_iconv ()
1410 {
1411     [ "$1" = "$2" ] && cat && return 0
1412     iconv -f "$1" -t "$2"
1413 }
1414 
1415 function help_myself ()
1416 {
1417     echo "argc = $#"
1418     echo "argv[0] = $0"
1419     i=1
1420     while [ "$1" ]
1421     do
1422         echo "argv[$i] = $1"
1423         i=$(($i+1))
1424         shift
1425     done
1426 }
1427 
1428 function help_obsolete ()
1429 {
1430     cat << ENDHELPMSG
1431  @@@ Obsolete Group: PATH Editor @@@
1432     old_path_editor
1433     old_ldpath_editor
1434  x  split_path
1435  x  split_path_core
1436  x  update_path 
1437  x  old_path_editor_core
1438 ENDHELPMSG
1439 }
1440 
1441 function help_function ()
1442 {
1443     [ "$#" = "0" ] && {
1444         cat << ENDHELPMSG
1445  <<< Help >>>
1446     help_myself [arguments ...]                            (helpm)
1447     help_function [functions ...]                          (helpf)
1448     help_obsolete
1449  x  print_iconv
1450 
1451  <<< Group: Background >>>
1452     bgrun command [arguments ...]                          (bgr)
1453     bglist [--full]                                        (bgl, bgls)
1454     bgview [number]                                        (bgv)
1455     bgclean [all | numbers ...]                            (bgrm)
1456     bgcount                                                (bgc)
1457     bgdu
1458  <<< Group: Trash >>>
1459     trash_mv [filenames ...] [-- sudo_prefix ...]     (trash_put, trash_add)
1460     trash_ls                                          (trash_list)
1461     trash_cd number
1462     trash_pushd number
1463     trash_recover numbers ... [-- sudo_prefix ...]    (trash_restore, trash_rc)
1464     trash_rm numbers ...                              (trash_drop, trash_clean)
1465     trash_count                                       (trash_ct)
1466     trash_du [-- sudo_prefix ...]
1467  <<< Group: New PATH Editor >>>
1468     path_editor [variable]
1469     ldpath_editor
1470  x  newpath_init
1471  x  newpath_gen
1472  <<< Group: Configuration File >>>
1473     configfile_fetch [file_name_list [file_version [system_type]]]
1474     configfile_initial_setup
1475  x  fetch_remote_file local_file_name remote_url
1476 
1477  <<< System: Terminal >>>
1478     set_console_title
1479     set_terminal_size
1480  <<< System: Information >>>
1481     get_memory_info
1482  <<< System: Packages Management >>>
1483     rpmdu [-kmg] packages ...
1484     rpmsize [-bkmg] packages ...
1485     freebsd_ports_should_rebuild
1486  <<< System: Privileges >>>
1487     keep_sudo_credential [seconds]
1488 
1489  <<< Tools: Interactive >>>
1490     compile_all [-n] filenames ...
1491     editlink filenames ... [-- sudo_prefix ...]
1492     mvfile [-n] filenames ... [-- sudo_prefix ...]
1493     varset variables ...
1494  <<< Tools: Non-interactive >>>
1495     backup_file filename ... [-- sudo_prefix ...]
1496     convert_to_html filename ...
1497     mkscreenacl usernames ...
1498 
1499  <<< Miscellaneous: Background Jobs >>>
1500     check_dmesg seconds
1501     check_system_status seconds
1502  <<< Miscellaneous: Compatibility >>>
1503     gen_ms_inet_shortcut filename url
1504     unzip_nomac filenames ...
1505  <<< Miscellaneous: Personal >>>
1506     check_important_files
1507     prehistory_backup
1508 
1509  <<< Shared Internal Functions >>>
1510  x  createdir_askmode dirname
1511  x  check_command_existent program
1512  x  is_file_type filename type [-- sudo_prefix ...]
1513  x  get_file_size filename [-- sudo_prefix ...]
1514  x  get_terminal_size
1515  x  split_arguments [arguments ...]
1516 
1517 Obsolete functions are not printed. Type \`help_obsolete' to print them.
1518 ENDHELPMSG
1519     } && return 0
1520     local current_charset=`echo "$LC_ALL" | cut -d . -f 2`
1521     local -i i
1522     while [ "$1" ]
1523     do
1524         case "$1" in
1525             help_myself|helpm)
1526                 cat << ENDHELPMSG | print_iconv "UTF-8" "$current_charset"
1527 help_myself
1528     一個測試命令列的小函式
1529 ENDHELPMSG
1530                 ;;
1531             help_function|helpf)
1532                 cat << ENDHELPMSG | print_iconv "UTF-8" "$current_charset"
1533 help_function
1534     顯示 .bash_include 提供的額外函式清單
1535     註:前方加上「x」符號者表示此為內部使用的函式,不宜直接使用
1536 ENDHELPMSG
1537                 ;;
1538             bgrun|bgr)
1539                 cat << ENDHELPMSG | print_iconv "UTF-8" "$current_charset"
1540 bgrun command [arguments ...]
1541     執行指令 command 並將輸出導入檔案
1542     註:此函式會自動以目前時間和指令名稱為檔案命名
1543 ENDHELPMSG
1544                 ;;
1545             bglist|bgl|bgls)
1546                 cat << ENDHELPMSG | print_iconv "UTF-8" "$current_charset"
1547 bglist [--full]
1548     列出所有使用 bgrun 執行的指令
1549     若加上 --full 選項,則可同時察看時間
1550 ENDHELPMSG
1551                 ;;
1552             bgview|bgv)
1553                 cat << ENDHELPMSG | print_iconv "UTF-8" "$current_charset"
1554 bgview [number]
1555     顯示以 bgrun 執行指令的輸出,若省略 number,表示是最近一次執行的指令
1556     若 number >  0,
1557         表示第 number 個指令 (此數值可由 bglist 函式取得)
1558     若 number <= 0,
1559         表示第「指令總數-number」個指令 (指令總數可由 bgcount 函式取得)
1560 ENDHELPMSG
1561                 ;;
1562             bgclean|bgrm)
1563                 cat << ENDHELPMSG | print_iconv "UTF-8" "$current_charset"
1564 bgclean [all | numbers ...]
1565     bgclean all 可清除所有指令的輸出檔
1566     bgclean 3 5 7 10 表示清除第 3、5、7、10 個指令輸出檔 (編號可由 bglist 取得)
1567 ENDHELPMSG
1568                 ;;
1569             bgcount|bgc)
1570                 cat << ENDHELPMSG | print_iconv "UTF-8" "$current_charset"
1571 bgcount
1572     顯示指令輸出檔總數
1573 ENDHELPMSG
1574                 ;;
1575             bgdu)
1576                 cat << ENDHELPMSG | print_iconv "UTF-8" "$current_charset"
1577 bgdu
1578     顯示每個指令輸出檔的檔案大小 (單位:KB)
1579 ENDHELPMSG
1580                 ;;
1581             *)
1582                 echo "Help message for $1 is not found"
1583                 ;;
1584         esac
1585         shift
1586     done
1587 }
1588 
1589 ########## Help End ##########
1590 
1591 # Doing something
1592 
1593 umask 0022
1594 
1595 if [ "$interactive_shell" ]
1596 then
1597     echo "Running interactive shell configuration"
1598     check_important_files
1599     startcolor
1600     prehistory_backup
1601     bind '"\e[A":history-search-backward'
1602     bind '"\e[B":history-search-forward'
1603     if [ -z "$PROMPT_COMMAND" ] && [ -e "$HOME/.bash_title" ]; then
1604         case "$TERM" in
1605             xterm*)
1606                 PROMPT_COMMAND='printf "\033]0;%s@%s:%s (%s)\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}" "`date "+%H:%M:%S"`"'
1607                 ;;
1608             screen*)
1609                 PROMPT_COMMAND='printf "\033]0;%s@%s:%s (%s)\033\\" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}" "`date "+%H:%M:%S"`"'
1610                 ;;
1611         esac
1612     fi
1613     [ "$TERM" = xterm ] && TERM=xterm-256color
1614     [ "$TERM" = screen ] && TERM=screen-256color
1615 fi
1616 
1617 if [ "`uname`" = "Linux" ]
1618 then
1619     [ "$interactive_shell" ] && echo "Setting special things for Linux"
1620     REALPATH_PROGRAM="readlink -f"
1621     ulimit -c unlimited
1622 fi
1623 
1624 [ "$interactive_shell" ] && echo "Setting shell options"
1625 
1626 shopt -s histappend
1627 shopt -s checkwinsize
1628 shopt -s checkjobs
1629 shopt -s checkhash
1630 shopt -s cmdhist
1631 shopt -s mailwarn
1632 
1633 [ "$interactive_shell" ] && {
1634     if [ "$WINDOW" ] && type screen &> /dev/null; then
1635         if [[ "`screen --version`" == *4.01* ]]; then
1636             echo "Setting options for GNU screen 4.1.0"
1637             screen -X cjkwidth off
1638         fi
1639     fi
1640 }
1641 
1642 [ "$interactive_shell" ] && {
1643     echo "Done"
1644     if [ "$UID" = "0" ] || [ "$EUID" = "0" ]
1645     then
1646         printf "\nNote: You may be \e[1;32mprivileged\e[m now!\n\n"
1647     fi
1648 }
1649