15 Bash

其实你应该把 bash 理解成一个跟桌面系统一样强大的程序。

Reference Manual

15.1 trouble shooting

  • disable XON/XOFF to avoid conflict with search forward
stty -ixon  # you can put it into ~/.bashrc
  • when your cursor disappear, echo -en "\e[?25h"

  • use \t in regexp

cat filename | sed -nE $'/pattern\t/p' 
cat filename | sed -nE '/pattern'$'\t''/p' # same as above

15.2 shortcut

move cursor
ctrl+a/e go to begin/end
ctrl+u/k delete to begin/end
copy & paste
ctrl+insert copy
shift+insert paste
search history
ctrl+r search backward
ctrl+s search forward
left/right select current line
enter excute current line

15.3 job control

One can use find / as example since it runs for a long time.

  • fg %n brings a job into the foreground
  • bg %n restarts a suspended background job
  • jobs lists jobs in the background
  • kill %n terminates a job

其中,n 是 job nubmer,fg, bg 默认为当前 job. more ways to specify a job.

So there are basically two ways to run a process in the background:

  1. Add & to the end of a command.
  2. Run a command, press C-z to suspend and throw to the background, then bg.

15.4 shell language

  • passing parameters
bar() {
    echo -e $1 '\t' $2
}
foo1 () {
    bar "$*"
}
foo2 () {
    bar "$@"
}

foo1 hello world
foo2 hello world
#> hello world  
#> hello     world
  • array

    1. array returns the first element, the same as array[0]
    2. @ or * means to get all elements of a array: ${array[@]} or ${array[*]}
    3. # means get element number
      • ${#array[@]} returns array length
      • ${#array} returns the length of the first element