Shell编程入门

hello world

#!/bin/bash

echo "hello world"

变量

定义变量:variable_name=variable_value
name="zhangsan"
使用变量:$variable_name
echo $name
替换
echo "name: $name"
只读、取消变量
readonly name
unset name

特殊变量

变量 描述
$0 当前脚本的文件名
$n 第一个参数是$1,第二个参数是$2
$# 参数的数量
$* All the arguments are double quoted.所有参数
$@ All the arguments are individually double quoted.所有参数
$? 上一个命令的退出状态
$$ 当前shell的进程号
$! 最后一个后台命令的进程号
echo "File Name: $0"
echo "First Parameter : $1"
echo "First Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"

运算

val=`expr a + b`

记下有以下几点:

  • 运算符和表达式之间必须有空格,例如2+2是不正确的,因为它应该写成2 + 2。
  • ``,称为倒逗号之间应包含完整的表达。
a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a * $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"

关系运算

if [ $a -eq $b ]
then
   echo "$a -eq $b : a is equal to b"
else
   echo "$a -eq $b: a is not equal to b"
fi

其他运算符

运算符 描述
-eq equal ==
-ne not equal !=
-gt greater than >
-lt less than <
-ge greater equal >=
-le less equal <=
! NOT !
-o OR
-a AND &&

字符串比较

运算符 描述
$a = $b "$a = $b : a is equal to b"
$a != $b "$a != $b : a is not equal to b"
-z "$a" "-z $a : string length is zero"
-n "$a" "-n $a : string length is not zero"
$a "$a : string is not empty"

if

a=10
b=20
if [ $a == $b ]
then
   echo "a is equal to b"
elif [ $a -gt $b ]
then
   echo "a is greater than b"
elif [ $a -lt $b ]
then
   echo "a is less than b"
else
   echo "None of the condition met"
fi

case

FRUIT="kiwi"
case "$FRUIT" in
   "apple") echo "Apple pie is quite tasty."
   ;;
   "banana") echo "I like banana nut bread."
   ;;
   "kiwi") echo "New Zealand is famous for kiwi."
   ;;
esac

while

a=0
while [ $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

for

for var in 0 1 2 3 4 5 6 7 8 9
do
   echo $var
done

until

a=0
until [ ! $a -lt 10 ]; do
    a=`expr $a + 1`
    echo $a
done

跳出循环break、continue

执行命令:command

DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"

${var} 等同$var
${var:-word} 如果var是null或unset,默认值
${var:=word} 如果var是null或unset,默认值,且赋值给var
${var:?message} 如果var为null或unset,则将消息打印为标准错误
${var:+word} 如果var存在,默认值

引用

元字符:* ? [ ] ' " $ ; & ( ) | ^ < > new-line space tab

echo "I have $1200" # 无法正确输出,需要:echo "I have \$1200"
echo 'I have $1200'

输入输出重定向

$ echo line 1 > users # 覆盖之前的数据
$ echo line 1 >> users # 追加到之前数据后

丢弃输出:
command > /dev/null
同时放弃输出和错误输出,2代表stderr和1代表STDOUT
command > /dev/null 2>&1

pgm > file pgm命令的输出重定向到file
pgm < file 程序pgm读取file的输入
pgm >> file 将pgm命令的输出追加到file中
| 从一个程序或进程中获取输出,并将其发送给另一个程序

函数

# 函数定义
Hello () {
   echo "Hello World $1 $2"
   return 10
}
# 方法调用
Hello
# 上一个命令的返回值
ret=$?
echo "Return value is $ret"

你可能感兴趣的:(Shell编程入门)