Bash语法速查:参数

neevop 十二月 6, 2022

Basics

name="John"
echo "${name}"
echo "${name/J/j}"    #=> "john" (substitution)
echo "${name:0:2}"    #=> "Jo" (slicing)
echo "${name::2}"     #=> "Jo" (slicing)
echo "${name::-1}"    #=> "Joh" (slicing)
echo "${name:(-1)}"   #=> "n" (slicing from right)
echo "${name:(-2):1}" #=> "h" (slicing from right)
echo "${food:-Cake}"  #=> $food or "Cake"
length=2
echo "${name:0:length}"  #=> "Jo"

See: Parameter expansion

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
str="Hello world"
echo "${str:6:5}"   # "world"
echo "${str: -5:5}"  # "world"
src="/path/to/foo.cpp"
base=${src##*/}   #=> "foo.cpp" (basepath)
dir=${src%$base}  #=> "/path/to/" (dirpath)

Substitution

Code Description
${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

Comments

# Single line comment
: '
This is a
multi line
comment
'

Substrings

Expression Description
${foo:0:3} Substring (position, length)
${foo:(-3):3} Substring from the right

Length

Expression Description
${#foo} Length of $foo

Manipulation

str="HELLO WORLD!"
echo "${str,}"   #=> "hELLO WORLD!" (lowercase 1st letter)
echo "${str,,}"  #=> "hello world!" (all lowercase)

str="hello world!"
echo "${str^}"   #=> "Hello world!" (uppercase 1st letter)
echo "${str^^}"  #=> "HELLO WORLD!" (all uppercase)

Transform strings

Command option Description
-c Operations apply to characters not in the given set
-d Delete characters
-s Replaces repeated characters with single occurrence
-t Truncates
[:upper:] All upper case letters
[:lower:] All lower case letters
[:digit:] All digits
[:space:] All whitespace
[:alpha:] All letters
[:alnum:] All letters and digits

Example

echo "Welcome To Devhints" | tr '[:lower:]' '[:upper:]'
WELCOME TO DEVHINTS

Directory of script

dir=${0%/*}

Default values

Expression Description
${foo:-val} $foo, or val if unset (or null)
${foo:=val} Set $foo to val if unset (or null)
${foo:+val} val if $foo is set (and not null)
${foo:?message} Show error message and exit if $foo is unset (or null)

Omitting the : removes the (non)nullity checks, e.g. ${foo-val} expands to val if unset otherwise $foo.

Special variables

Expression Description
$? Exit status of last task
$! PID of last background task
$$ PID of shell
$0 Filename of the shell script
$_ Last argument of the previous command
${PIPESTATUS[n]} return value of piped commands (array)

See Special parameters.

Numeric calculations

$((a + 200))      # Add 200 to $a
$(($RANDOM%200))  # Random number 0..199