我與 Bash (tips)

最後更新: 2023-04-21

目錄

  • Check Current Bash Version
  • Which shell you are using
  • seq
  • log ot stdout
  •  

Check Current Bash Version

 

應用: ${BASH_VERSION}

[方式1]

echo "${BASH_VERSION}"

4.2.46(2)-release         # Centos 7 default bash version

[方式2] Hotkey

Ctrl+x Ctrl+v

 


Which shell you are using

 

應用: $0 / $SHELL / $$

echo $0                 # -bash

OR

echo $SHELL          # /bin/bash

OR

ps -p "$$"              # $$ = 當前 shell 的 pid

  PID TTY          TIME CMD
 4080 pts/10   00:00:00 bash

 


seq

 

seq 1 5

1
2
3
4
5

 


log ot stdout

 

echo "This is an Error message." >&2

 


{..} 的應用

 

[test1]

echo {1..5}    # 錯誤: { 1..10 }, {1 .. 10}, { 1 .. 10 }

Result:

1 2 3 4 5

[test2]

echo {a..e}

a b c d e

[test3]

a=1; c=5; echo {$a..$c}

{1..5}

方法:

eval echo {$a..$c}

 


|&

 

| 的 stderr ( |&  shortcut for 2>&1 | )

* 只有 bash 才有

 


Redirecting

 

redirecting standard output and standard

cmd &> word

    相當於

cmd >word 2>&1

P.S.

係沒有 &>> 的 @@

Redirect stderr To stdout

cmd ... 2>&1

cmd1 |& cmd2

 


Shell Prompt

 

PS = prompt statement

Bash 一共有 4 個 PS, 分別是 PS1 ~ PS4

PS1 – Default interaction prompt

PS2 – Continuation interactive prompt

"COMMAND \" 之後出現 '>'

PS3 – Prompt used by "select" inside shell script

PS4 – Used by "set -x" to prefix tracing output

"++"

PROMPT_COMMAND

Bash shell executes the content of the PROMPT_COMMAND just before displaying the PS1

# Show only current directory name (not full path) on bash prompt

Change the \w (lowercase) to \W (uppercase)

 


Run an interactive subshell(bash) with initial commands

 

應用: --init-file

Default: --init-file ~/.bashrc

[1]

echo "ls; pwd" > initfile

bash --init-file initfile

[2]

bash --init-file <(echo "ls; pwd")

 

 


Toggle flag

 

# Use the bitwise XOR-equal operator to flip between the two values

應用: ((...))^=

flag=0
((flag ^= 1))
echo $flag
((flag ^= 1))
echo $flag

 


Kill Loop(until)

 

應用 Var: %%

IP=192.168.0.254
until ping -c1 $IP &>/dev/null; do echo "waiting"; done

Ctrl+C 係 stop 唔到佢 !! 要 Ctrl-Z 之後 kill %%

 


mkdir 之後 cd

 

 

目的: cd 到 last element of the previous command line argument

i.e. 應用 Var: !$

mkdir /usr/src/ffmpeg;
cd !$
pwd                                       # Checking

 * 不可以寫成 mkdir /usr/src/ffmpeg; cd !$

P.S.

  • "!" - usually relates to the history commands
  • "!^" - for the first argument
  • "!*" - all arguments from previous command
  • "!n" - command number n from history
  • "!pattern" - most recent command matching pattern

 

 

 

Creative Commons license icon Creative Commons license icon