1. 概述
shell中有两类字符:普通字符、元字符。
-
普通字符
在Shell中除了本身的字面意思外没有其他特殊意义,即普通纯文本; -
元字符
是Shell的保留字符,在Shell中有着特殊的含义。
今天主要介绍一下shell中字符 $ 、## 和 %% 的各种用法。
2. 转义字符$的用法
示例一:
#!/bin/bash
if [ -z "$1" ];then
echo "Usage:$0 + 参数"
exit -1
fi
total=$[ $1 + $2 ]
echo "\$[ \$1 + \$2 ] = $total"
echo "\$0 shell script name:$0"
echo "\$1 the first arg:$1"
echo "\$# the number of args:$#"
echo "\$? the return value of last cmd:$?"
echo "\$$ the current PID:$$"
echo "\$@ the list of args:$@"
echo "\$* the list of args with one string:$*"
执行结果如下:
示例二:
index=1
echo "input args with \$*:" #traverse one by one
for arg in $*
do
echo "arg:$index = $arg"
let index+=1
done
echo
index=1
echo "input args with \"\$*\":" #traverse once as the whole string
for arg in "$*"
do
echo "arg:$index = $arg"
let index+=1
done
echo
index=1
echo "input args with \$@:" #traverse one by one
for arg in $@
do
echo "arg:$index = $arg"
let index+=1
done
echo
index=1
echo "input args with \"\$@\":" #traverse one by one
for arg in "$@"
do
echo "arg:$index = $arg"
let index+=1
done
echo
3. ${}、##和%%的用法
假设定义了一个变量为:
代码如下:
file=/dir1/dir2/dir3/my.file.txt
可以用${ }分别替换得到不同的值:
${file#/}:删掉第一个 / 及其左边的字符串:dir1/dir2/dir3/my.file.txt
${file##/}:删掉最后一个 / 及其左边的字符串:my.file.txt
${file#.}:删掉第一个 . 及其左边的字符串:file.txt
${file##.}:删掉最后一个 . 及其左边的字符串:txt
${file%/}:删掉最后一个 / 及其右边的字符串:/dir1/dir2/dir3
${file%%/}:删掉第一个 / 及其右边的字符串:(空值)
${file%.}:删掉最后一个 . 及其右边的字符串:/dir1/dir2/dir3/my.file
${file%%.}:删掉第一个 . 及其右边的字符串:/dir1/dir2/dir3/my
记忆的方法为:
#是去掉左边(键盘上#在 $ 的左边)
%是去掉右边(键盘上% 在$ 的右边) 单一符号是最小匹配;
两个符号是最大匹配
${file:0:5}:提取最左边的 5 个字节:/dir1
${file:5:5}:提取第 5 个字节右边的连续5个字节:/dir2
也可以对变量值里的字符串作替换:
${file/dir/path}:将第一个dir替换为path:/path1/dir2/dir3/my.file.txt
${file//dir/path}:将全部dir 替换为path:/path1/path2/path3/my.file.txt