logo
🐧 Linux 命令

Bash

Bash Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · Linux 命令🧭 Markdown 速查🏷️ 2 个标签
#bash#shell
向下滚动查看内容
返回全部 Cheat Sheets

Getting Started

hello.sh
BASH
滚动查看更多
#!/bin/bash

VAR="world"
echo "Hello $VAR!" # => Hello world!

Execute the script

SHELL
滚动查看更多
$ bash hello.sh
Variables
BASH
滚动查看更多
NAME="John"

echo ${NAME}    # => John (Variables)
echo $NAME      # => John (Variables)
echo "$NAME"    # => John (Variables)
echo '$NAME'    # => $NAME (Exact string)
echo "${NAME}!" # => John! (Variables)

NAME = "John"   # => Error (about space)
Comments
BASH
滚动查看更多
# This is an inline Bash comment.
BASH
滚动查看更多
: '
This is a
very neat comment
in bash
'

Multi-line comments use :' to open and ' to close

Arguments
ExpressionDescription
$1$9Parameter 1 ... 9
$0Name of the script itself
$1First argument
${10}Positional parameter 10
$#Number of arguments
$$Process id of the shell
$*All arguments
$@All arguments, starting from first
$-Current options
$_Last argument of the previous command

See: Special parameters

Functions
BASH
滚动查看更多
get_name() {
    echo "John"
}

echo "You are $(get_name)"

See: Functions

Conditionals
BASH
滚动查看更多
if [[ -z "$string" ]]; then
    echo "String is empty"
elif [[ -n "$string" ]]; then
    echo "String is not empty"
fi

See: Conditionals

Brace expansion
BASH
滚动查看更多
echo {A,B}.js

ExpressionDescription
{A,B}Same as A B
{A,B}.jsSame as A.js B.js
{1..5}Same as 1 2 3 4 5

See: Brace expansion

Shell execution
BASH
滚动查看更多
# => I'm in /path/of/current
echo "I'm in $(PWD)"

# Same as:
echo "I'm in `pwd`"

See: Command substitution

Bash Parameter expansions

Syntax
CodeDescription
${FOO%suffix}Remove suffix
${FOO#prefix}Remove prefix
${FOO%%suffix}Remove long suffix
${FOO##prefix}Remove long prefix
${FOO/from/to}Replace first match
${FOO//from/to}Replace all
${FOO/%from/to}Replace suffix
${FOO/#from/to}Replace prefix

Substrings

ExpressionDescription
${FOO:0:3}Substring (position, length)
${FOO:(-3):3}Substring from the right

Length

ExpressionDescription
${#FOO}Length of $FOO

Default values

ExpressionDescription
${FOO:-val}$FOO, or val if unset
${FOO:=val}Set $FOO to val if unset
${FOO:+val}val if $FOO is set
${FOO:?message}Show message and exit if $FOO is unset
Substitution
BASH
滚动查看更多
echo ${food:-Cake}  #=> $food or "Cake"
BASH
滚动查看更多
STR="/path/to/foo.cpp"
echo ${STR%.cpp}    # /path/to/foo
echo ${STR%.cpp}.o  # /path/to/foo.o
echo ${STR%/*}      # /path/to

echo ${STR##*.}     # cpp (extension)
echo ${STR##*/}     # foo.cpp (basepath)

echo ${STR#*/}      # path/to/foo.cpp
echo ${STR##*/}     # foo.cpp

echo ${STR/foo/bar} # /path/to/bar.cpp
Slicing
BASH
滚动查看更多
name="John"
echo ${name}           # => John
echo ${name:0:2}       # => Jo
echo ${name::2}        # => Jo
echo ${name::-1}       # => Joh
echo ${name:(-1)}      # => n
echo ${name:(-2)}      # => hn
echo ${name:(-2):2}    # => hn

length=2
echo ${name:0:length}  # => Jo

See: Parameter expansion

basepath & dirpath
BASH
滚动查看更多
SRC="/path/to/foo.cpp"
BASH
滚动查看更多
BASEPATH=${SRC##*/}
echo $BASEPATH  # => "foo.cpp"


DIRPATH=${SRC%$BASEPATH}
echo $DIRPATH   # => "/path/to/"
Transform
BASH
滚动查看更多
STR="HELLO WORLD!"
echo ${STR,}   # => hELLO WORLD!
echo ${STR,,}  # => hello world!

STR="hello world!"
echo ${STR^}   # => Hello world!
echo ${STR^^}  # => HELLO WORLD!

ARR=(hello World)
echo "${ARR[@],}" # => hello world
echo "${ARR[@]^}" # => Hello World

Bash Arrays

Defining arrays
BASH
滚动查看更多
Fruits=('Apple' 'Banana' 'Orange')

Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[2]="Orange"

ARRAY1=(foo{1..2}) # => foo1 foo2
ARRAY2=({A..D})    # => A B C D

# Merge => foo1 foo2 A B C D
ARRAY3=(${ARRAY1[@]} ${ARRAY2[@]})

# declare construct
declare -a Numbers=(1 2 3)
Numbers+=(4 5) # Append => 1 2 3 4 5
Indexing
--
${Fruits[0]}First element
${Fruits[-1]}Last element
${Fruits[*]}All elements
${Fruits[@]}All elements
${#Fruits[@]}Number of all
${#Fruits}Length of 1st
${#Fruits[3]}Length of nth
${Fruits[@]:3:2}Range
${!Fruits[@]}Keys of all
Iteration
BASH
滚动查看更多
Fruits=('Apple' 'Banana' 'Orange')

for e in "${Fruits[@]}"; do
    echo $e
done

With index

BASH
滚动查看更多
for i in "${!Fruits[@]}"; do
  printf "%s\t%s\n" "$i" "${Fruits[$i]}"
done

Operations
BASH
滚动查看更多
Fruits=("${Fruits[@]}" "Watermelon")     # Push
Fruits+=('Watermelon')                   # Also Push
Fruits=( ${Fruits[@]/Ap*/} )             # Remove by regex match
unset Fruits[2]                          # Remove one item
Fruits=("${Fruits[@]}")                  # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}")  # Concatenate
lines=(`cat "logfile"`)                  # Read from file
Arrays as arguments
BASH
滚动查看更多
function extract()
{
    local -n myarray=$1
    local idx=$2
    echo "${myarray[$idx]}"
}
Fruits=('Apple' 'Banana' 'Orange')
extract Fruits 2     # => Orangle

Bash Dictionaries

Defining
BASH
滚动查看更多
declare -A sounds
BASH
滚动查看更多
sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"
Working with dictionaries
BASH
滚动查看更多
echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]}   # All values
echo ${!sounds[@]}  # All keys
echo ${#sounds[@]}  # Number of elements
unset sounds[dog]   # Delete dog
Iteration
BASH
滚动查看更多
for val in "${sounds[@]}"; do
    echo $val
done

BASH
滚动查看更多
for key in "${!sounds[@]}"; do
    echo $key
done

Bash Conditionals

Integer conditions
ConditionDescription
[[ NUM -eq NUM ]]<yel>Eq</yel>ual
[[ NUM -ne NUM ]]<yel>N</yel>ot <yel>e</yel>qual
[[ NUM -lt NUM ]]<yel>L</yel>ess <yel>t</yel>han
[[ NUM -le NUM ]]<yel>L</yel>ess than or <yel>e</yel>qual
[[ NUM -gt NUM ]]<yel>G</yel>reater <yel>t</yel>han
[[ NUM -ge NUM ]]<yel>G</yel>reater than or <yel>e</yel>qual
(( NUM < NUM ))Less than
(( NUM <= NUM ))Less than or equal
(( NUM > NUM ))Greater than
(( NUM >= NUM ))Greater than or equal
String conditions
ConditionDescription
[[ -z STR ]]Empty string
[[ -n STR ]]<yel>N</yel>ot empty string
[[ STR == STR ]]Equal
[[ STR = STR ]]Equal (Same above)
[[ STR < STR ]]Less than (ASCII)
[[ STR > STR ]]Greater than (ASCII)
[[ STR != STR ]]Not Equal
[[ STR =~ STR ]]Regexp
Example

String

BASH
滚动查看更多
if [[ -z "$string" ]]; then
    echo "String is empty"
elif [[ -n "$string" ]]; then
    echo "String is not empty"
else
    echo "This never happens"
fi

Combinations

BASH
滚动查看更多
if [[ X && Y ]]; then
    ...
fi

Equal

BASH
滚动查看更多
if [[ "$A" == "$B" ]]; then
    ...
fi

Regex

BASH
滚动查看更多
if [[ '1. abc' =~ ([a-z]+) ]]; then
    echo ${BASH_REMATCH[1]}
fi

Smaller

BASH
滚动查看更多
if (( $a < $b )); then
   echo "$a is smaller than $b"
fi

Exists

BASH
滚动查看更多
if [[ -e "file.txt" ]]; then
    echo "file exists"
fi
File conditions
ConditionDescription
[[ -e FILE ]]<yel>E</yel>xists
[[ -d FILE ]]<yel>D</yel>irectory
[[ -f FILE ]]<yel>F</yel>ile
[[ -h FILE ]]Symlink
[[ -s FILE ]]Size is > 0 bytes
[[ -r FILE ]]<yel>R</yel>eadable
[[ -w FILE ]]<yel>W</yel>ritable
[[ -x FILE ]]Executable
[[ f1 -nt f2 ]]f1 <yel>n</yel>ewer <yel>t</yel>han f2
[[ f1 -ot f2 ]]f2 <yel>o</yel>lder <yel>t</yel>han f1
[[ f1 -ef f2 ]]Same files
More conditions

| Condition | Description | | -------------------- | -------------------- | ----- | --- | | [[ -o noclobber ]] | If OPTION is enabled | | [[ ! EXPR ]] | Not | | [[ X && Y ]] | And | | [[ X | | Y ]] | Or |

logical and, or
BASH
滚动查看更多
if [ "$1" = 'y' -a $2 -gt 0 ]; then
    echo "yes"
fi

if [ "$1" = 'n' -o $2 -lt 0 ]; then
    echo "no"
fi

Bash Loops

Basic for loop
BASH
滚动查看更多
for i in /etc/rc.*; do
    echo $i
done
C-like for loop
BASH
滚动查看更多
for ((i = 0 ; i < 100 ; i++)); do
    echo $i
done
Ranges
BASH
滚动查看更多
for i in {1..5}; do
    echo "Welcome $i"
done

With step size

BASH
滚动查看更多
for i in {5..50..5}; do
    echo "Welcome $i"
done
Continue
BASH
滚动查看更多
for number in $(seq 1 3); do
    if [[ $number == 2 ]]; then
        continue;
    fi
    echo "$number"
done
Break
BASH
滚动查看更多
for number in $(seq 1 3); do
    if [[ $number == 2 ]]; then
        # Skip entire rest of loop.
        break;
    fi
    # This will only print 1
    echo "$number"
done
Until
BASH
滚动查看更多
count=0
until [ $count -gt 10 ]; do
    echo "$count"
    ((count++))
done
While with increment
BASH
滚动查看更多
i=1
while [[ $i -lt 4 ]]; do
    echo "Number: $i"
    ((i++))
done
While with decrement
BASH
滚动查看更多
i=3
while [[ $i -gt 0 ]]; do
    echo "Number: $i"
    ((i--))
done

Combined with test

BASH
滚动查看更多
i=3
while ((i--)); do
    echo "Number: $i"
done
Forever
BASH
滚动查看更多
while true; do
    # here is some code.
done
Forever (shorthand)
BASH
滚动查看更多
while :; do
    # here is some code.
done
Reading lines
BASH
滚动查看更多
while read line; do
    echo $line
done < file.txt

Bash Functions

Defining functions
BASH
滚动查看更多
myfunc() {
    echo "hello $1"
}
BASH
滚动查看更多
# Same as above (alternate syntax)
function myfunc() {
    echo "hello $1"
}
BASH
滚动查看更多
myfunc "John"
Returning values
BASH
滚动查看更多
myfunc() {
    local myresult='some value'
    echo $myresult
}
BASH
滚动查看更多
result="$(myfunc)"
Raising errors
BASH
滚动查看更多
myfunc() {
    return 1
}
BASH
滚动查看更多
if myfunc; then
    echo "success"
else
    echo "failure"
fi

Bash Options

Options
BASH
滚动查看更多
# Avoid overlay files
# (echo "hi" > foo)
set -o noclobber

# Used to exit upon error
# avoiding cascading errors
set -o errexit

# Unveils hidden failures
set -o pipefail

# Exposes unset variables
set -o nounset
Glob options
BASH
滚动查看更多
# Non-matching globs are removed
# ('*.foo' => '')
shopt -s nullglob

# Non-matching globs throw errors
shopt -s failglob

# Case insensitive globs
shopt -s nocaseglob

# Wildcards match dotfiles
# ("*.sh" => ".foo.sh")
shopt -s dotglob

# Allow ** for recursive matches
# ('lib/**/*.rb' => 'lib/a/b/c.rb')
shopt -s globstar

Bash History

Commands
CommandDescription
historyShow history
sudo !!Run the previous command with sudo
shopt -s histverifyDon't execute expanded result immediately
Expansions
ExpressionDescription
!$Expand last parameter of most recent command
!*Expand all parameters of most recent command
!-nExpand nth most recent command
!nExpand nth command in history
!<command>Expand most recent invocation of command <command>
Operations
CodeDescription
!!Execute last command again
!!:s/<FROM>/<TO>/Replace first occurrence of <FROM> to <TO> in most recent command
!!:gs/<FROM>/<TO>/Replace all occurrences of <FROM> to <TO> in most recent command
!$:tExpand only basename from last parameter of most recent command
!$:hExpand only directory from last parameter of most recent command

!! and !$ can be replaced with any valid expansion.

Slices
CodeDescription
!!:nExpand only nth token from most recent command (command is 0; first argument is 1)
!^Expand first argument from most recent command
!$Expand last token from most recent command
!!:n-mExpand range of tokens from most recent command
!!:n-$Expand nth token to last from most recent command

!! can be replaced with any valid expansion i.e. !cat, !-2, !42, etc.

Miscellaneous

Numeric calculations
BASH
滚动查看更多
$((a + 200))      # Add 200 to $a
BASH
滚动查看更多
$(($RANDOM%200))  # Random number 0..199
Subshells
BASH
滚动查看更多
(cd somedir; echo "I'm now in $PWD")
pwd # still in first directory
Inspecting commands
BASH
滚动查看更多
command -V cd
#=> "cd is a function/alias/whatever"
Redirection
BASH
滚动查看更多
python hello.py > output.txt   # stdout to (file)
python hello.py >> output.txt  # stdout to (file), append
python hello.py 2> error.log   # stderr to (file)
python hello.py 2>&1           # stderr to stdout
python hello.py 2>/dev/null    # stderr to (null)
python hello.py &>/dev/null    # stdout and stderr to (null)
BASH
滚动查看更多
python hello.py < foo.txt      # feed foo.txt to stdin for python
Source relative
BASH
滚动查看更多
source "${0%/*}/../share/foo.sh"
Directory of script
BASH
滚动查看更多
DIR="${0%/*}"
Case/switch
BASH
滚动查看更多
case "$1" in
    start | up)
    vagrant up
    ;;

    *)
    echo "Usage: $0 {start|stop|ssh}"
    ;;
esac
Trap errors
BASH
滚动查看更多
trap 'echo Error at about $LINENO' ERR

or

BASH
滚动查看更多
traperr() {
    echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
}

set -o errtrace
trap traperr ERR
printf
BASH
滚动查看更多
printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga

printf "1 + 1 = %d" 2
#=> "1 + 1 = 2"

printf "Print a float: %f" 2
#=> "Print a float: 2.000000"
Getting options
BASH
滚动查看更多
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
    -V | --version )
    echo $version
    exit
    ;;
    -s | --string )
    shift; string=$1
    ;;
    -f | --flag )
    flag=1
    ;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi
Check for command's result
BASH
滚动查看更多
if ping -c 1 google.com; then
    echo "It appears you have a working internet connection"
fi
Special variables
ExpressionDescription
$?Exit status of last task
$!PID of last background task
$$PID of shell
$0Filename of the shell script

See Special parameters.

Grep check
BASH
滚动查看更多
if grep -q 'foo' ~/.bash_history; then
    echo "You appear to have typed 'foo' in the past"
fi
Backslash escapes
  •  
  • !
  • "
  • #
  • &
  • '
  • (
  • )
  • ,
  • ;
  • <
  • >
  • [
  • |
  • \
  • ]
  • ^
  • {
  • }
  • `
  • $
  • *
  • ?

{.cols-4 .marker-none}

Escape these special characters with \

Heredoc
SH
滚动查看更多
cat <<END
hello world
END
Go to previous directory
BASH
滚动查看更多
pwd # /home/user/foo
cd bar/
pwd # /home/user/foo/bar
cd -
pwd # /home/user/foo
Reading input
BASH
滚动查看更多
echo -n "Proceed? [y/n]: "
read ans
echo $ans
BASH
滚动查看更多
read -n 1 ans    # Just one character
Conditional execution
BASH
滚动查看更多
git commit && git push
git commit || echo "Commit failed"
Strict mode
BASH
滚动查看更多
set -euo pipefail
IFS=$'\n\t'

See: Unofficial bash strict mode

Optional arguments
BASH
滚动查看更多
args=("$@")
args+=(foo)
args+=(bar)
echo "${args[@]}"

Put the arguments into an array and then append

Also see

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572