关键字用法
basename
~/Desktop cat a.sh
echo $(basename "$0")
echo $0
~/Desktop sh a.sh
a.sh
a.sh
~/Desktop sh ~/Desktop/a.sh
a.sh
/Users/yangkaiyue/Desktop/a.sh
local
~/Desktop cat a.sh
defA() {
local aa=10
bb=20
echo aa: $aa
echo bb: $bb
}
defA
echo aa: $aa
echo bb: $bb
~/Desktop sh a.sh
aa: 10
bb: 20
aa:
bb: 20
shift
~/Desktop cat a.sh
echo $@
shift
echo $@
~/Desktop sh a.sh 1 2 3 4
1 2 3 4
2 3 4
~/Desktop cat a.sh
a() {
echo $@
shift 2
echo $@
}
a 1 2 3 4
~/Desktop sh a.sh
1 2 3 4
3 4
readonly
~/Desktop cat a.sh
readonly z=0
echo $z
z=3
echo $z
~/Desktop sh a.sh
0
a.sh: line 4: z: readonly variable
expr
echo `expr 2 + 3`
$ 的使用
echo $?
echo $0
echo $1~$n
echo $#
echo $$
~/Desktop cat a.sh
for i in "$@";do
echo $i
done
for i in "$*";do
echo $i
done
~/Desktop sh a.sh 1 2 3
1
2
3
1 2 3
${} - 变量相关
字符串截取
file=/dir1/dir2/dir3/my.file.txt
${file:0:5}
${file:5:5}
字符串删除
file=/dir1/dir2/dir3/my.file.txt
${file#*/}
${file##*/}
${file%/*}
${file%%/*}
字符串替换
file=/dir1/dir2/dir3/my.file.txt
${file/dir/path}
${file//dir/path}
设置默认值
~/Desktop cat a.sh
a="my_var"
my_var="Hello, World"
b="Fallback Value"
result1="${a:-$b}"
result2="${c:-$b}"
result3="${!a:-$b}"
echo $result1
echo $result2
echo $result
~/Desktop sh a.sh
my_var
Fallback Value
Hello, World
其他
${#var}
${file-my.file.txt} :假如$file 沒有设定,則使用my.file.txt 作传回值。(空值及非空值時不作处理)
${file:-my.file.txt} :假如$file 沒有設定或為空值,則使用my.file.txt 作傳回值。(非空值時不作处理)
${file+my.file.txt} :假如$file 設為空值或非空值,均使用my.file.txt 作傳回值。(沒設定時不作处理)
${file:+my.file.txt} :若$file 為非空值,則使用my.file.txt 作傳回值。(沒設定及空值時不作处理)
${file=my.file.txt} :若$file 沒設定,則使用my.file.txt 作傳回值,同時將$file 賦值為my.file.txt 。(空值及非空值時不作处理)
${file:=my.file.txt} :若$file 沒設定或為空值,則使用my.file.txt 作傳回值,同時將$file 賦值為my.file.txt 。(非空值時不作处理)
${file?my.file.txt} :若$file 沒設定,則將my.file.txt 輸出至STDERR。(空值及非空值時不作处理)
变量为空报错 - ${var:?msg}
~/Desktop cat a.sh
echo ${file:?"var file not exist"}
echo "end"
~/Desktop sh a.sh
a.sh: line 3: file: var file not exist
数组的使用
定义
arr=(1 2 3)
arr[3]=4
使用
echo ${#arr[@]}
echo ${#arr[*]}
echo ${!arr[@]}
echo ${!arr[*]}
echo ${arr[@]}
echo ${arr[*]}
echo arr[0]
echo arr[1]
for i in ${arr[@]};do
echo $i
done
for i in ${!arr@]};do
if [ $i = 2 ];then
echo ${arr$i]}
fi
done
容错
位置参数为空
if [[ $# -nq 4 ]];then
exit 99
fi
age=${1:-18}
if [[ -z $1 ]];then
exit 99
fi
常用
`` - 执行命令
a=`date`
echo $a
$() - 执行命令
b=$(date)
echo $b
$(()) - 计算
echo $((2+3))
[] 和 [[]] - 对比判断
参考链接
- https://www.cnblogs.com/pugang/p/13167714.html