bash and dash

bash and dash

"在 UbuntuLive 上的 Tutorial 學到一些不錯得東西"

隨手記錄一下摟

宣告變數時

\${name:-default}

\${name:=default}

\${name:+altvalue}

\${name:?derrmsg}

remove leading text

\${name#pre}

\${name##pre}

範例:

thomas@T-DRBL:\~\$ name=thomas at nchc //宣告

thomas@T-DRBL:\~\$ echo \${name#thomas}

@nchc

thomas@T-DRBL:\~\$ echo \${name##thomas}

@nchc

thomas@T-DRBL:\~\$ echo \${name#thomas*} //比對到 thomas止

@nchc

thomas@T-DRBL:\~\$ echo \${name##thomas*} //比對到thomas 包含後面所有字元直到最後面止,所以沒有結果

thomas@T-DRBL:\~\$ echo \${name##thomas*nc}

hc

remove trailing text

\${name%post}

\${name%%post}

範例:

thomas@T-DRBL:\~\$ echo \${name%nchc}

thomas@

thomas@T-DRBL:\~\$ echo \${name%%nchc}

thomas@

thomas@T-DRBL:\~\$ echo \${name%*nchc}

thomas@

thomas@T-DRBL:\~\$ echo \${name%%*nchc}

thomas@T-DRBL:\~\$ echo \${name%%@*hc}

thomas

subtitle

\${name/pattern/string}

\${name//pattern/string}

範例:

echo \${name/thomas/th}

th@nchc

substring

\${name:offset}

\${name:offset:length}

string length

\${#name}

範例:

thomas@T-DRBL:\~\$ echo \${name:5:3} //第5個字起後3個字元

s@n

thomas@T-DRBL:\~\$ echo \${name:0:\${#name}}

thomas at nchc

Arrays

declare -a name

name[2]="xxx"

echo \${name[2]}

echo \${name[*]}

regular expression

if \$a =\~ \$b

if \$a == \$b

if \$a != \$b

if 表示法

[ \$var ] && cat \$var

//也就是

if [ \$var ] then

cat \$var

fi

//的縮寫表示法

run a command

\$(cmd)

var=\$(ls) //better

cat file

\$(cat file) //slower

\$(< file) //faster

convert from Thomas blog post id 143 old convert log: ./153927/tag%3E2007%2007%20linux)

@2007 @07 @linux

Comments