linux shell笔记

 新建 test.sh
运行命令 sh test.sh
 
1.打印hello word
echo "hello word"
 
2.打印变量
str="hello word"
echo $str 或者 echo ${str}
 
3.环境变量
$PATH, $HOME, $PWD, $USER, $UID, $SHELL等
 
4.获得字符串长度
echo ${#变量名}
 
例如: s="test"
 
echo ${#s}  返回结果:4
 
6.算术运算
 
在Bash shell环境中,可以利用let, (( ))和[ ]执行基本的算数操作.而在进行高级操作时,expr和bc这两个工具也会非常有用.
let n=1+5
 
echo $n
 
let n++
 
let n--
 
let n+=6
 
n=$[ 1+5 ]
 
n=$(( 1+5 ))
 
n=`expr 3 + 4`
 
以上不支持浮点数,只用于整数运算.
 
bc是一个用于数据运算的高级工具,可以借助它执行浮点数运算.
 
echo "4 * 0.56" | bc
 
no=58
 
result=`echo "$no * 1.5" | bc`
 
echo $result
 
7.文件描述符和重定向
 
文件描述符是与文件输入,输出相关联的整数,用来跟踪已打开的文件,最常见的文件描述符
0 --- 标准输入(stdin)
1 --- 标准输出(stdout)
2 --- 标准错误(stderr)
 
echo "this is a sample text 1" > temp.txt
 
用下面的方法可以将输出文件重定向或保存到一个文件中
echo "this is a sample text 1" > temp.txt
 
8.数组
array_var=(1 2 3 4 5 6) --用空格分隔
 
另外还可以这样初始化数组, array_var[0]="test1"
 
打印特定索引的数组元素 echo ${array_var[0]}
 
如index=5
 
echo ${array_var[$index]}
 
以清单形式打印数组中的所有值: echo ${array_var[*]}  或者 echo ${array_var[@]}
 
打印数组长度: echo ${#array_var[*]} 或者 echo ${#array_var[@]}
 
9.read :从终端读取一行数据给后面的变量
    read A
    输入1234
    echo A
    打印出1234
 
10. test 比较2个字符串是否相等,相等为0,不等为1
    A="HEllo" 
    B="World"
    test $A = $B
    test $A != $B
    C=""
    test -n $C   测试C的字符串长度是否不为0
    test -z $C   测试C的字符串长度是否为0
 
#! /bin/bash
A="hello"
B="hello"
test $A = $B
echo "result = $?"
 
11. 整数测试
a -eq b 测试a与b是否相等
  -ne  不相等
  -gt  大于
  -ge  大于等于 
  -lt  小于
  -le  小于等于
 
#! /bin/bash
a=5
b=5
test $a -eq $b
echo "result = $?"
 
12. 文件测试
-d name  测试name是否为一个目录
-f name  测试name石否为普通文件
-L 是否为符号链接
-r 是否存在且为可读
-w  是否存在且为可写
-x 是否存在且为可执行
-s 是否存在且其长度不为0
f1 -nt f2  测试文件f1是否比f2更新
f1 -ot f2  测试文件f1石否比f2更旧
 
test -d "/home/rubydev"
echo "result = $?"
 
 
13. 条件语句
    1. if...then...fi
        if 表达式
            then 命令表
        fi 表达式
 
if [ -d "/home/rubydev" ]
then
    echo "/home/rubydev is d"
fi
 
if …; then
elif …; then
else
fi
 
14. 数组
arr=(1 2 3 4 5)
echo ${arr[@]}
 
for i in "${arr[@]}"
do
  echo "$i"
done
 
15.shell编程怎么抽取匹配正则表达式的字符串?
 
a=$( expr 'helloworld20140501.txt' : '.*([0-9]{8}).*' )
echo $a
 
20140501
 
16.循环
#!/bin/bash
for (( i = 0; i < 10; i++ ))
do
   if [ $i = 5 ]; then
     continue
   fi
   echo $i
done
原文地址:https://www.cnblogs.com/songfei90/p/10195015.html