shell 惯用指令笔记
num=2
echo "this is the $numnd" 不会显示2 --》echo "this is the ${num}nd"
-----------------------------------------
first=3 ; sec=5 ; echo `expr $first \* $sec` 显示15
s=$((3+5));echo $s
first=3 ; sec=5 ; s=$(($fisrt+5))
-----------------------------------------
for file in /etc/* /var/log/jetty/*;do
...
done
---------------------
$? 前一个命令的返回码
$! 上一个进程的进程号
--------------------
wc -l file 行数
wc -w file 单词数
wc -c file 字符数
basename /bin/java 返回java
dirname /bin/java 返回 /bin
tail file 文件末尾几行 常用 tail -f jetty.log
head file 文件前几行
sort file | uniq
cp -r dir dir2
mv file file2
rm -rf file
ln -s TARGET LINK_NAME
------------------------
tar zcvf file.tar.gz `find . -name jdk*`
tar zcvf file.tar.gz `find . -mtime -1` 24小时内
--------------------------
if [ ... ];then
...
elif [ ... ];then
...
else
fi
-------------
if [ ... ] && [ ... ];then
if [ ... ] || [ ... ];then
[表达式1 -a 表达式2] 2个表达式都为真则真
[表达式1 -o 表达式2] 任一表达式都为真则真
---------------------------------------
整数
if [ "$a" -eq "$b"];then //相等 if [ "$a" -ne "$b"];then //不相等 if [ "$a" -gt "$b"];then //大于 if [ "$a" -ge "$b"];then //大于相等 if [ "$a" -lt "$b"];then //小于 if [ "$a" -le "$b"];then //小于相等 if [ (("$a" > "$b")) ];then //相等
字符串
if [ "$a" = "$b"];then //相等 if [ "$a" == "z*"];then //字符匹配 a等于“z*” if [ $a == z* ];then //模式匹配 z开头 if [[ "$a" > "$b"]];then //双括号 if [ "$a" \> "$b"];then //单括号转义 -z 长度为0 -n 字符串不为空
文件
[ -d $file] 存在且为目录 [ -e $file] 存在 [ -f "somefile"] 是否文件(目录也不行)
[ -s "somefile"] 文件存在且不为空
[ -x $file] 存在且可执行 [ -r $file] 存在且可读 [ -w $file] 存在且可写 [ -h $file] 存在且为链接 [ -S $file] 存在且为Socket [(表达式)] [!(表达式)]
------------------------------------
case $str in "2"*) do something;; "3"*) do something;; *) do something;; esac
select var in ("ab" "cd" "ef");do break done echo "$var" while ...;do ... done for i in "$arr[@]";do ... done for i in A B C;do ... done
数组
arr=("ab" "cd" "ef") str="ab cd ef"; arr=($str) //字符串转数组 num=${#arr[@]} 数字的size unset arr 重置数组 ${arr[@]}和${arr[*]} echo ${arr} //默认第一个元素 --------------------- #!/bin/sh str=“15 25 68” arr=($str) count=${#arr[@]} for((i=0; i<count; i+=1));do echo "${arr[$i]}" done --------------------- $# 参数个数 $@ 和 $* 参数列表 //所有.jpg结尾的文件 for name in *.jpg:do echo $name done
数学表达式
total=`expr $first \* $sec` expr 30 / 3 / 2 打印5 // 运算符左右都有空格 ,如果没有空格表示是字符串连接 如果试图计算非整数,将返回错误。 $value=12 $expr $value + 10 > /dev/null 2>&1 模式匹配 value=accounts.doc $expr $value : '.*' expr通过指定冒号选项计算字符串中字符数。 expr $value : '(.*).doc' accounts expr substr "this is a test" 3 5 is is