前言 Bash Shell作为Linux的指定合作伙伴我们已经再熟悉不过了,使用Bash可以快速编写简单的脚本方便我们的日常比如善用vim
,awk
和sed
三剑客,也可以创建十分复杂的逻辑,当然我更愿意推荐你使用Python代替,之前一直没有刻意去整理因为平时常用的就这么几个,有些经验和技巧都是在实战中形成和记录,需要使用的时候知道大概用什么,查下相关语法和案例即可。
Bash命令语法和Bash Cheat Sheet中文速查表
更新历史 2020年04月23日 - 增加阮一峰编写的《Bash 教程》 2019年10月29日 - 初稿
阅读原文 - https://wsgzao.github.io/post/bash/
Bash 脚本教程
如果觉得阮一峰的Bash教程还意犹未尽,可以浏览参考文章中的Bash相关链接
Bash 是 Linux 和 Mac 的默认 Shell(命令行环境),系统管理和服务器开发都需要它。虽然不难,但是语法很怪异,根本记不住,需要查手册。网上找不到简明扼要的中文教程,我很早就想整理一个,方便自己日后使用。
我一共写了20节,Bash 脚本编程的主要语法,都包括在内了,日常使用应该足够。点击这个链接 ,现在就可以自由阅读和访问。也欢迎初学者使用这个教程,学习 Bash。
https://wangdoc.com/bash/
http://www.ruanyifeng.com/blog/2020/04/bash-tutorial.html
LearnBash-cn.sh https://learnxinyminutes.com/docs/zh-cn/bash-cn/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 echo Hello world!echo 'This is the first line' ; echo 'This is the second line' Variable="Some string" Variable = "Some string" Variable= 'Some string' echo $Variable echo "$Variable " echo '$Variable' echo ${Variable/Some/A} Length=7 echo ${Variable:0:Length} echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} echo "Last program return value: $?" echo "Script's PID: $$" echo "Number of arguments: $# " echo "Scripts arguments: $@ " echo "Scripts arguments separated in different variables: $1 $2 ..." echo "What's your name?" read Name echo Hello, $Name !if [ $Name -ne $USER ]then echo "Your name isn't your username" else echo "Your name is your username" fi echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" if [ $Name == "Steve" ] && [ $Age -eq 15 ]then echo "This will run if $Name is Steve AND $Age is 15." fi if [ $Name == "Daniya" ] || [ $Name == "Zach" ]then echo "This will run if $Name is Daniya OR Zach." fi echo $(( 10 + 5 ))ls ls -l ls -l | grep "\.txt" cat > hello.py << EOF #!/usr/bin/env python from __future__ import print_function import sys print("#stdout", file=sys.stdout) print("#stderr", file=sys.stderr) for line in sys.stdin: print(line, file=sys.stdout) EOF python hello.py < "input.in" python hello.py > "output.out" python hello.py 2> "error.err" python hello.py > "output-and-error.log" 2>&1 python hello.py > /dev/null 2>&1 python hello.py >> "output.out" 2>> "error.err" info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.errecho <(echo "#helloworld" )cat > output.out <(echo "#helloworld" )echo "#helloworld" > output.outecho "#helloworld" | cat > output.outecho "#helloworld" | tee output.out >/dev/nullrm -v output.out error.err output-and-error.logecho "There are $(ls | wc -l) items here." echo "There are `ls | wc -l` items here." case "$Variable " in 0) echo "There is a zero." ;; 1) echo "There is a one." ;; *) echo "It is not null." ;; esac for Variable in {1..3}do echo "$Variable " done for ((a=1 ; a <= 3 ; a++))do echo $a done for Variable in file1 file2do cat "$Variable " done for Output in $(ls )do cat "$Output " done while [ true ]do echo "loop body here..." break done function foo (){ echo "Arguments work just like script arguments: $@ " echo "And: $1 $2 ..." echo "This is a function" return 0 } bar (){ echo "Another way to declare functions!" return 0 } foo "My name is" $Name tail -n 10 file.txthead -n 10 file.txtsort file.txtuniq -d file.txtcut -d ',' -f 1 file.txtsed -i 's/okay/great/g' file.txt grep "^foo.*bar$" file.txt grep -c "^foo.*bar$" file.txt fgrep "^foo.*bar$" file.txt help help help help for help return help source help .apropos bash man 1 bash man bash apropos info | grep '^info.*(' man info info info info 5 info info bash info bash 'Bash Features' info bash 6 info --apropos bash
bash.sh 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 CTRL+A CTRL+B CTRL+C CTRL+D CTRL+E CTRL+F CTRL+G CTRL+H CTRL+K CTRL+L CTRL+N CTRL+O CTRL+P CTRL+R CTRL+S CTRL+T CTRL+U CTRL+V CTRL+W CTRL+X CTRL+Y CTRL+Z CTRL+_ ALT+b ALT+d ALT+f ALT+t ALT+BACKSPACE CTRL+X CTRL+X CTRL+X CTRL+E exit env echo $SHELL bash which bash whereis bash whatis bash clear reset cd cd {dirname } pwd mkdir {dirname } mkdir -p {dirname } pushd {dirname } popd dirs -v cd - cd -{N} ls ls -l ls -1 ls -a ln -s {fn} {link } cp {src} {dest} rm {fn} mv {src} {dest} touch {fn} cat {fn} any_cmd > {fn} more {fn} less {fn} head {fn} tail {fn} tail -f {fn} nano {fn} vim {fn} diff {f1} {f2} wc {fn} chmod 644 {fn} chgrp group {fn} chown user1 {fn} file {fn} basename {fn} dirname {fn} grep {pat} {fn} grep -r {pat} . stat {fn} whoami who w users passwd finger {user} adduser {user} deluser {user} w su su - su {user} su -{user} id {user} id -u {user} id -g {user} write {user} last last {user} lastb lastlog sudo {command } ps ps ax ps aux ps auxww ps -u {user} ps axjf ps xjf -u {user} ps -eo pid,user,command ps aux | grep httpd ps --ppid {pid} pstree pstree {user} pstree -u pgrep {procname} kill {pid} kill -9 {pid} kill -KILL {pid} kill -l kill -l TERM killall {procname} pkill {procname} top top -u {user} any_command & jobs bg fg fg {job} trap cmd sig1 sig2 trap "" sig1 sig2 trap - sig1 sig2 nohup {command } nohup {command } & disown {PID|JID} wait ssh user@host ssh -p {port} user@host ssh-copy-id user@host scp {fn} user@host:path scp user@host:path dest scp -P {port} ... uname -a man {help } man -k {keyword} info {help } uptime date cal vmstat vmstat 10 free df du uname hostname showkey -a ping {host} ping -c N {host} traceroute {host} mtr {host} host {domain} whois {domain} dig {domain} route -n netstat -a netstat -an netstat -anp netstat -l netstat -t netstat -lntu netstat -lntup netstat -i netstat -rn ss -an ss -s wget {url} wget -qO- {url} curl -sL {url} sz {file} rz varname=value varname=value command echo $varname echo $$ echo $! echo $? export VARNAME=value array[0]=valA array[1]=valB array[2]=valC array=([0]=valA [1]=valB [2]=valC) array=(valA valB valC) ${array[i]} ${#array[@]} ${#array[i]} declare -a declare -f declare -F declare -i declare -r declare -x declare -p varname ${varname:-word} ${varname:=word} ${varname:?message} ${varname:+word} ${varname:offset:len} ${variable#pattern} ${variable##pattern} ${variable%pattern} ${variable%%pattern} ${variable/pattern/str} ${variable//pattern/str} ${#varname} *(patternlist) +(patternlist) ?(patternlist) @(patternlist) !(patternlist) array=($text ) IFS="/" array=($text ) text="${array[*]} " text=$(IFS=/; echo "${array[*]} " ) A=( foo bar "a b c" 42 ) B=("${A[@]:1:2} " ) C=("${A[@]:1} " ) echo "${B[@]} " echo "${B[1]} " echo "${C[@]} " echo "${C[@]: -2:2} " $(UNIX command ) varname=$(id -u user) num=$(expr 1 + 2) num=$(expr $num + 1) expr 2 \* \( 2 + 3 \) num=$((1 + 2 )) num=$(($num + 1 )) num=$((num + 1 )) num=$((1 + (2 + 3 ) * 2 )) !! !^ !$ !string !^string1^string2 ! function myfunc () { {shell commands ...} } myfunc myfunc arg1 arg2 arg3 myfunc "$@ " myfunc "${array[@]} " shift unset -f myfunc declare -f statement1 && statement2 statement1 || statement2 exp1 -a exp2 exp1 -o exp2 ( expression ) ! expression str1 = str2 str1 != str2 str1 < str2 str2 > str2 -n str1 -z str1 -a file -d file -e file -f file -r file -s file -w file -x file -N file -O file -G file file1 -nt file2 file1 -ot file2 num1 -eq num2 num1 -ne num2 num1 -lt num2 num1 -le num2 num1 -gt num2 num1 -ge num2 test {expression} [ expression ] test "abc" = "def" test "abc" != "def" test -a /tmp; echo $? [ -a /tmp ]; echo $? test cond && cmd1 [ cond ] && cmd1 [ cond ] && cmd1 || cmd2 if test -e /etc/passwd; then echo "alright it exists ... " else echo "it doesn't exist ... " fi if [ -e /etc/passwd ]; then echo "alright it exists ... " else echo "it doesn't exist ... " fi [ -e /etc/passwd ] && echo "alright it exists" || echo "it doesn't exist" if [ "$varname " = "foo" ]; then echo "this is foo" elif [ "$varname " = "bar" ]; then echo "this is bar" else echo "neither" fi if [ $x -gt 10 ] && [ $x -lt 20 ]; then echo "yes, between 10 and 20" fi [ $x -gt 10 ] && [ $x -lt 20 ] && echo "yes, between 10 and 20" if [ \( $x -gt 10 \) -a \( $x -lt 20 \) ]; then echo "yes, between 10 and 20" fi [ \( $x -gt 10 \) -a \( $x -lt 20 \) ] && echo "yes, between 10 and 20" [ -x /bin/ls ] && /bin/ls -l https://www.ibm.com/developerworks/library/l-bash-test/index.html while condition; do statements done i=1 while [ $i -le 10 ]; do echo $i ; i=$(expr $i + 1) done for i in {1..10}; do echo $i done for name [in list]; do statements done for f in /home/*; do echo $f done for (( initialisation ; ending condition ; update )); do statements done for ((i = 0 ; i < 10 ; i++)); do echo $i ; done case expression in pattern1 ) statements ;; pattern2 ) statements ;; * ) otherwise ;; esac until condition; do statements done select name [in list]; do statements that can use $name done command ls builtin cd enable help {builtin_command} eval $script cmd1 | cmd2 < file > file >> file >| file n>| file <> file n<> file n> file n< file n>& n<& n>&m n<&m &>file <&- >&- n>&- n<&- diff <(cmd1) <(cmd2) cut -c 1-16 cut -c 1-16 file cut -c3- cut -d':' -f5 cut -d';' -f2,10 cut -d' ' -f3-7 echo "hello" | cut -c1-3 echo "hello sir" | cut -d' ' -f2 ps | tr -s " " | cut -d " " -f 2,3,4 awk '{print $5}' file awk -F ',' '{print $5}' file awk '/str/ {print $2}' file awk -F ',' '{print $NF}' file awk '{s+=$1} END {print s}' file awk 'NR%3==1' file sed 's/find/replace/' file sed '10s/find/replace/' file sed '10,20s/find/replace/' file sed -r 's/regex/replace/g' file sed -i 's/find/replace/g' file sed -i '/find/i\newline' file sed -i '/find/a\newline' file sed '/line/s/find/replace/' file sed -e 's/f/r/' -e 's/f/r' file sed 's#find#replace#' file sed -i -r 's/^\s+//g' file sed '/^$/d' file sed -i 's/\s\+$//' file sed -n '2p' file sed -n '2,5p' file sort file sort -r file sort -n file sort -t: -k 3n /etc/passwd sort -u file source /path/to/z.sh z z foo z foo bar z -l foo z -r foo z -t foo bind '"\eh":"\C-b"' bind '"\el":"\C-f"' bind '"\ej":"\C-n"' bind '"\ek":"\C-p"' bind '"\eH":"\eb"' bind '"\eL":"\ef"' bind '"\eJ":"\C-a"' bind '"\eK":"\C-e"' bind '"\e;":"ls -l\n"' ip a ip a show eth1 ip a add 172.16.1.23/24 dev eth1 ip a del 172.16.1.23/24 dev eth1 ip link show dev eth0 ip link set eth1 up ip link set eth1 down ip link set eth1 address {mac} ip neighbour ip route ip route add 10.1.0.0/24 via 10.0.0.253 dev eth0 ip route del 10.1.0.0/24 ifconfig ifconfig -a ifconfig eth0 ifconfig eth0 up ifconfig eth0 down ifconfig eth0 192.168.120.56 ifconfig eth0 10.0.0.8 netmask 255.255.255.0 up ifconfig eth0 hw ether 00:aa:bb:cc:dd :ee nmap 10.0.0.12 nmap -p 1024-65535 10.0.0.12 nmap 10.0.0.0/24 nmap -O -sV 10.0.0.12 man hier man test man ascii getconf LONG_BIT bind -P mount | column -t curl ip.cn disown -a && exit cat /etc/issue lsof -i port:80 showkey -a svn diff | view - mv filename.{old,new} time read cp file.txt{,.bak} sudo touch /forcefsck find ~ -mmin 60 -type f curl wttr.in/~beijing echo ${SSH_CLIENT%% *} echo $[RANDOM%X+1] bind -x '"\C-l":ls -l' find / -type f -size +5M chmod --reference f1 f2 curl -L cheat.sh history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head netstat -n | awk '/^tcp/ {++tt[$NF]} END {for (a in tt) print a, tt[a]}' sshfs name@server:/path/to/folder /path/to/mount/point ps aux | sort -nk +4 | tail while sleep 1;do tput sc;tput cup 0 $(($(tput cols)-29 ));date ;tput rc;done &wget -qO - "http://www.tarball.com/tarball.gz" | tar zxvf - python -c "import test.pystone;print(test.pystone.pystones())" dd if =/dev/zero of=/dev/null bs=1M count=32768mount /path/to/file.iso /mnt/cdrom -oloop ssh -t hostA ssh hostB wget -r -l1 --no-parent -nH -nd -P/tmp -A".gif,.jpg" http://example.com/images mkdir -p work/{project1,project2}/{src,bin,bak}find . -type f -newermt "2010-01-01" ! -newermt "2010-06-01" lsof -P -i -n | cut -f 1 -d " " | uniq | tail -n +2 :w !sudo tee > /dev/null % source ~/github/profiles/my_bash_init.shssh -CqTnN -R 0.0.0.0:8443:192.168.1.2:443 user@202.115.8.1 ssh -CqTnN -L 0.0.0.0:8443:192.168.1.2:443 user@192.168.1.3 ssh -CqTnN -D localhost:1080 user@202.115.8.1 http://www.skywind.me/blog/archives/2021 function q-extract () { if [ -f $1 ] ; then case $1 in *.tar.bz2) tar -xvjf $1 ;; *.tar.gz) tar -xvzf $1 ;; *.tar.xz) tar -xvJf $1 ;; *.bz2) bunzip2 $1 ;; *.rar) rar x $1 ;; *.gz) gunzip $1 ;; *.tar) tar -xvf $1 ;; *.tbz2) tar -xvjf $1 ;; *.tgz) tar -xvzf $1 ;; *.zip) unzip $1 ;; *.Z) uncompress $1 ;; *.7z) 7z x $1 ;; *) echo "don't know how to extract '$1 '..." ;; esac else echo "'$1 ' is not a valid file!" fi } function q-compress () { if [ -n "$1 " ] ; then FILE=$1 case $FILE in *.tar) shift && tar -cf $FILE $* ;; *.tar.bz2) shift && tar -cjf $FILE $* ;; *.tar.xz) shift && tar -cJf $FILE $* ;; *.tar.gz) shift && tar -czf $FILE $* ;; *.tgz) shift && tar -czf $FILE $* ;; *.zip) shift && zip $FILE $* ;; *.rar) shift && rar $FILE $* ;; esac else echo "usage: q-compress <foo.tar.gz> ./foo ./bar" fi } function ccat () { local style="monokai" if [ $# -eq 0 ]; then pygmentize -P style=$style -P tabsize=4 -f terminal256 -g else for NAME in $@ ; do pygmentize -P style=$style -P tabsize=4 -f terminal256 -g "$NAME " done fi } export LESS_TERMCAP_mb=$'\E[1m\E[32m' export LESS_TERMCAP_mh=$'\E[2m' export LESS_TERMCAP_mr=$'\E[7m' export LESS_TERMCAP_md=$'\E[1m\E[36m' export LESS_TERMCAP_ZW="" export LESS_TERMCAP_us=$'\E[4m\E[1m\E[37m' export LESS_TERMCAP_me=$'\E(B\E[m' export LESS_TERMCAP_ue=$'\E[24m\E(B\E[m' export LESS_TERMCAP_ZO="" export LESS_TERMCAP_ZN="" export LESS_TERMCAP_se=$'\E[27m\E(B\E[m' export LESS_TERMCAP_ZV="" export LESS_TERMCAP_so=$'\E[1m\E[33m\E[44m' "\eh" : backward-char"\el" : forward-char"\ej" : next-history"\ek" : previous-history"\eH" : backward-word"\eL" : forward-word"\eJ" : beginning-of-line"\eK" : end-of-linehttps://github.com/Idnan/bash-guide http://www.linuxstall.com/linux-command-line-tips-that-every-linux-user-should-know/ https://ss64.com/bash/syntax-keyboard.html http://wiki.bash-hackers.org/commands/classictest https://www.ibm.com/developerworks/library/l-bash-test/index.html https://www.cyberciti.biz/faq/bash-loop-over-file/ https://linuxconfig.org/bash-scripting-tutorial https://github.com/LeCoupa/awesome-cheatsheets/blob/master/languages/bash.sh https://devhints.io/bash https://github.com/jlevy/the-art-of-command-line https://yq.aliyun.com/articles/68541
参考文章 Bash 教程
LearnBash-cn.sh
Bash awesome-cheatsheets
bash-step-to-step
Linux 上,最常用的一批命令解析(10 年精选)