Linux Shell编程入门

bash是Linux标准默认的shell

注意:bash是 Bourne Again Shell 的缩写,是linux标准的默认shell ,它基于Bourne shell,吸收了C shell和Korn shell的一些特性。bash完全兼容sh,也就是说,用sh写的脚本可以不加修改的在bash中执行。

1、第一个Shell脚本,HelloWorld

1.1 编辑脚本文件

[root@master ~]# mkdir shell

[root@master ~]# cd shell

[root@master shell]# vi hello

#!/bin/bash
echo "Hello World !"

解释:“#!” 是一个约定的标记,它告诉系统这个脚本需要什么解释器来执行,即使用哪一种Shell。echo命令用于向窗口输出文本

1.2 运行脚本

第1种,脚本文件作为sh命令的参数

[root@master shell]# sh hello
Hello World !

第2种,脚本文件作为可执行文件

[root@master shell]# chmod +x hello
[root@master shell]# ./hello
Hello World !

注意,在当前目录运行可执行文件需要加上“./”,表示当前目录。若直接输入可执行文件名,可能提示找不到该命令

[root@master shell]# hello

-bash: hello: command not found


2、Shell变量

2.1 定义与使用

  与其他编程语言不一样,定义Shell 变量时变量名不能以$开头,变量赋值时,和等号之间不能有空格。使用一个定义过的变量,只要在变量名前面加美元符号($)即可。

[root@master shell]# vi hello2

#!/bin/bash
s="Hello World!"
echo $s
echo ${s}
echo "print:${s}"

[root@master shell]# sh hello2
Hello World!
Hello World!
print:Hello World!

说明:单独使用变量时,{}括号可以省略,当在表达式中时需要加上,标示变量范围;输出字符串时,${}表达式将被计算,

看起来,很像EL表达式。

2.2 只读变量与删除变量

使用 readonly 命令可以将变量定义为只读变量,只读变量的值不能被改变。

使用 unset 命令可以删除变量

[root@master shell]# vi var

#!/bin/bash
readonly s="Hello World!"
echo "readonly s=$s"
s1="OK"
echo "s1=$s1"
unset s1
echo "s1=${s1}"
unset s
echo "只读变量不能删除s=${s}"
[root@master shell]# sh var

readonly s=Hello World!
s1=OK
s1=
var: line 8: unset: s: cannot unset: readonly variable
只读变量不能删除s=Hello World!


2.3 变量类型
运行shell时,会同时存在三种变量:
1) 局部变量
局部变量在脚本或命令中定义,仅在当前shell实例中有效,其他shell启动的程序不能访问局部变量。
2) 环境变量
所有的程序,包括shell启动的程序,都能访问环境变量,有些程序需要环境变量来保证其正常运行。必要的时候shell脚本也可以定义环境变量。
3) shell变量
shell变量是由shell程序设置的特殊变量。shell变量中有一部分是环境变量,有一部分是局部变量,这些变量保证了shell的正常运行。

一般Shell变量名只能包含数字、字母和下划线,因为某些包含其他字符的变量有特殊含义,这样的变量被称为特殊变量。

特殊变量列表
变量 含义
$0当前脚本的文件名
$n传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。
$#传递给脚本或函数的参数个数。
$*传递给脚本或函数的所有参数。
$@传递给脚本或函数的所有参数。被双引号(" ")包含时,与 $* 稍有不同,下面将会讲到。
$?上个命令的退出状态,或函数的返回值。
$$当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。

[root@master shell]# vi var2

#!/bin/bash
echo "当前脚本: $0"
echo "第1个参数: $1"
echo "第2个参数: $2"
echo "所有参数\$@: $@"
echo "所有参数\$*: $*"
echo "参数个数: $#"
echo $?

[root@master shell]# sh var2 a b c

当前脚本: var2
第1个参数: a
第2个参数: b
所有参数$@: a b c
所有参数$*: a b c
参数个数: 3

0

注意:退出状态是一个数字,一般情况下,大部分命令执行成功会返回 0,失败返回 1。不过,也有一些命令返回其他值,表示不同类型的错误。$? 也可以表示函数的返回值。


3、Shell替换


形式 说明
${var}变量本来的值
${var:-word}如果变量 var 为空或已被删除(unset),那么返回 word,但不改变 var 的值。
${var:=word}如果变量 var 为空或已被删除(unset),那么返回 word,并将 var 的值设置为 word。
${var:?message}如果变量 var 为空或已被删除(unset),那么将消息 message 送到标准错误输出,可以用来检测变量 var 是否可以被正常赋值。
若此替换出现在Shell脚本中,那么脚本将停止运行。
${var:+word}如果变量 var 被定义,那么返回 word,但不改变 var 的值。

[root@master shell]# vi replace

#!/bin/bash
#转义字符, -e 表示对转义字符进行替换
a=10
echo -e "Value of a is $a \n"
#命令替换
echo "Date is `date`"
#变量替换
echo ${var:-"Variable is not set"}
echo "1 - Value of var is ${var}"
echo ${var:="Variable is not set"}
echo "2 - Value of var is ${var}"
unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"
var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"
echo ${var:?"Print this message"}
echo "5 - Value of var is ${var}"
[root@master shell]# sh replace 

Value of a is 10 

Date is Mon Feb  6 20:46:43 CST 2017
Variable is not set
1 - Value of var is 
Variable is not set
2 - Value of var is Variable is not set

3 - Value of var is 
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix


4、Shell运算符

算术运算符列表
运算符 说明 举例
+加法`expr $a + $b` 结果为 30。
-减法`expr $a - $b` 结果为 10。
*乘法`expr $a \* $b` 结果为  200。
/除法`expr $b / $a` 结果为 2。
%取余`expr $b % $a` 结果为 0。
=赋值a=$b 将把变量 b 的值赋给 a。
==相等。用于比较两个数字,相同则返回 true。[ $a == $b ] 返回 false。
!=不相等。用于比较两个数字,不相同则返回 true。[ $a != $b ] 返回 true。

原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如 expr;

在Shell中进行算术运算的方法:

1)let表达式

      let c=$a + $b

2) $[算术表达式]

     c=$[$a+$b]

3) $((算术表达式))

    c=$(($a+$b))

4)expr表达式

expr 是一款表达式计算工具,使用它能完成表达式的求值操作。

表达式和运算符之间要有空格,例如 2+2 是不对的,必须写成 2 + 2,这与我们熟悉的大多数编程语言不一样


关系运算符列表
运算符 说明 举例
-eq检测两个数是否相等,相等返回 true。[ $a -eq $b ] 返回 true。
-ne检测两个数是否相等,不相等返回 true。[ $a -ne $b ] 返回 true。
-gt检测左边的数是否大于右边的,如果是,则返回 true。[ $a -gt $b ] 返回 false。
-lt检测左边的数是否小于右边的,如果是,则返回 true。[ $a -lt $b ] 返回 true。
-ge检测左边的数是否大等于右边的,如果是,则返回 true。[ $a -ge $b ] 返回 false。
-le检测左边的数是否小于等于右边的,如果是,则返回 true。[ $a -le $b ] 返回 true。

布尔运算符列表
运算符 说明 举例
!非运算,表达式为 true 则返回 false,否则返回 true。[ ! false ] 返回 true。
-o或运算,有一个表达式为 true 则返回 true。[ $a -lt 20 -o $b -gt 100 ] 返回 true。
-a与运算,两个表达式都为 true 才返回 true。[ $a -lt 20 -a $b -gt 100 ] 返回 false。

字符串运算符列表
运算符 说明 举例
=检测两个字符串是否相等,相等返回 true。[ $a = $b ] 返回 false。
!=检测两个字符串是否相等,不相等返回 true。[ $a != $b ] 返回 true。
-z检测字符串长度是否为0,为0返回 true。[ -z $a ] 返回 false。
-n检测字符串长度是否为0,不为0返回 true。[ -z $a ] 返回 true。
str检测字符串是否为空,不为空返回 true。[ $a ] 返回 true。
[root@master shell]# vi operator

#!/bin/sh
a=10
b=20
echo "算术运算"
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"
echo "比较运算"
if [ $a == $b ]
then
   echo "a is equal to b"
fi
if [ $a != $b ]
then
   echo "a is not equal to b"
fi
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
if [ $a -ne $b ]
then
   echo "$a -ne $b: a is not equal to b"
else
   echo "$a -ne $b : a is equal to b"
fi
if [ $a -gt $b ]
then
then
   echo "$a -lt 100 -o $b -gt 100 : returns true"
else
   echo "$a -lt 100 -o $b -gt 100 : returns false"
fi
echo "字符串运算"
a="abc"
b="efg"
if [ $a = $b ]
then
   echo "$a = $b : a is equal to b"
else
   echo "$a = $b: a is not equal to b"
fi
if [ $a != $b ]
then
   echo "$a != $b : a is not equal to b"
else
   echo "$a != $b: a is equal to b"
fi
if [ -z $a ]
then
   echo "-z $a : string length is zero"
else
   echo "-z $a : string length is not zero"
fi
if [ -n $a ]
then
   echo "-n $a : string length is not zero"
else
   echo "-n $a : string length is zero"
fi
if [ $a ]
then
   echo "$a : string is not empty"
else
   echo "$a : string is empty"
fi
[root@master shell]# sh operator 

算术运算
a + b : 30
a - b : -10
a * b : 200
b / a : 2
b % a : 0
比较运算
a is not equal to b
10 -eq 20: a is not equal to b
10 -ne 20: a is not equal to b
10 -gt 20: a is not greater than b
10 -lt 20: a is less than b
10 -ge 20: a is not greater or equal to b
10 -le 20: a is less or  equal to b
逻辑运算
10 -lt 100 -a 20 -gt 15 : returns true
10 -lt 100 -o 20 -gt 100 : returns true
字符串运算
abc = efg: a is not equal to b
abc != efg : a is not equal to b
-z abc : string length is not zero
-n abc : string length is not zero
abc : string is not empty

文件测试运算符列表
操作符 说明 举例
-b file检测文件是否是块设备文件,如果是,则返回 true。[ -b $file ] 返回 false。
-c file检测文件是否是字符设备文件,如果是,则返回 true。[ -b $file ] 返回 false。
-d file检测文件是否是目录,如果是,则返回 true。[ -d $file ] 返回 false。
-f file检测文件是否是普通文件(既不是目录,也不是设备文件),如果是,则返回 true。[ -f $file ] 返回 true。
-g file检测文件是否设置了 SGID 位,如果是,则返回 true。[ -g $file ] 返回 false。
-k file检测文件是否设置了粘着位(Sticky Bit),如果是,则返回 true。[ -k $file ] 返回 false。
-p file检测文件是否是具名管道,如果是,则返回 true。[ -p $file ] 返回 false。
-u file检测文件是否设置了 SUID 位,如果是,则返回 true。[ -u $file ] 返回 false。
-r file检测文件是否可读,如果是,则返回 true。[ -r $file ] 返回 true。
-w file检测文件是否可写,如果是,则返回 true。[ -w $file ] 返回 true。
-x file检测文件是否可执行,如果是,则返回 true。[ -x $file ] 返回 true。
-s file检测文件是否为空(文件大小是否大于0),不为空返回 true。[ -s $file ] 返回 true。
-e file检测文件(包括目录)是否存在,如果是,则返回 true。[ -e $file ] 返回 true。
文件测试运算符用于检测 Unix 文件的各种属性

[root@master shell]# vi operator2

#!/bin/sh
file="/var/www/tutorialspoint/unix/test.sh"
if [ -r $file ]
then
   echo "File has read access"
else
   echo "File does not have read access"
fi
if [ -w $file ]
then
   echo "File has write permission"
else
   echo "File does not have write permission"
fi
if [ -x $file ]
then
   echo "File has execute permission"
else
   echo "File does not have execute permission"
fi
if [ -f $file ]
then
   echo "File is an ordinary file"
else
   echo "This is sepcial file"
fi
if [ -d $file ]
then
   echo "File is a directory"
else
   echo "This is not a directory"
fi
if [ -s $file ]
then
   echo "File size is zero"
else
   echo "File size is not zero"
fi
if [ -e $file ]
then
   echo "File exists"
else
   echo "File does not exist"
fi
[root@master shell]# sh operator2 
File has read access
File has write permission
File does not have execute permission
File is an ordinary file
This is not a directory
File size is zero
File exists


5、字符串

[root@master shell]# vi string 

#!/bin/sh
echo '单引号里的任何字符都会原样输出\n'
echo "双引号中的字符串可以有变量和转义字符"
#拼接字符串
name="xiaoming"
h1="hello, "$name" !"
h2="hello, ${name} !"
echo $h1 $h2
#字符串长度
string="abcd"
echo ${#string} 
echo `expr length $string`
#提取子字符串
string="alibaba is a great company"
echo ${string:1:4} #输出liba
#查找子串
string="alibaba is a great company"
echo `expr index "$string" is`

[root@master shell]# sh string 
单引号里的任何字符都会原样输出\n
双引号中的字符串可以有变量和转义字符
hello, xiaoming ! hello, xiaoming !
4
4
liba
3

注意:expr index $string substring索引命令功能在字符串$string上找出substring中字符(不是字符串)第一次出现的位置,若找不到则expr index返回0或1。

6、Shell数组

bash支持一维数组(不支持多维数组),并且没有限定数组的大小。类似与C语言,数组下标由0开始。

在Shell中,用括号来表示数组,数组元素用“空格”符号分割开。定义数组的一般形式为:
    array_name=(value1 ... valuen)

[root@master shell]# vi array

#!/bin/sh
a=("c" "c++" "java")
echo ${a[0]} ${a[1]} ${a[2]}
a[3]="C#"
echo ${a[3]}
echo ${a[*]}
echo ${a[@]}
echo ${#a[*]} ${#a[@]}
[root@master shell]# sh array

c c++ java
C#
c c++ java C#
c c++ java C#
4 4

7、输出语句

echo是Shell的一个内部指令,用于在屏幕上打印出指定的字符串

echo本身带有换行效果。在sh标准下echo"OK!\nIt is a test"在ok和It之间有换行效果,而使用bash标准下只有echo -e“OK\nIt is a test”ok 和 it 之间才会有换行效果

printf 命令用于格式化输出, 是echo命令的增强版。它是C语言printf()库函数的一个有限的变形,printf 不像 echo 那样会自动换行,必须显式添加换行符(\n)。

[root@master shell]# vi echo

#!/bin/sh
echo -e "OK!\c"
echo "a test"
#显示结果重定向至文件
echo "a test" > a.txt
echo "abc" >> a.txt
printf "%d %s\n" 1 "abc"
# 没有引号也可以输出
printf %s abcdef
# 格式只指定了一个参数,多出的参数仍然会按照该格式输出
printf %s abc def
[root@master shell]# sh echo

OK!a test
1 abc
abcdefabcdef[root@master shell]#

[root@master shell]# cat a.txt
a test
abc

8、分支语句

1) if ... else 语句语法:

if [ expression ]
then
   Statement(s) to be executed if expression is true
fi

注意:expression 和方括号[ ]之间必须有空格,否则会有语法错误。

2) if ... else ... fi 语句语法:
if [ expression ]
then
   Statement(s) to be executed if expression is true
else

   Statement(s) to be executed if expression is not true
fi

3) if ... elif ... fi 语句语法:
if [ expression 1 ]
then
   Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi

[root@master shell]# vi elif

#!/bin/sh
a=$1
b=$2
if test $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
[root@master shell]# sh elif 10 20

a is less than b
[root@master shell]# sh elif 10 10
a is equal to b

说明:test 命令用于检查某个条件是否成立,与方括号([ ])类似

case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构。

case 语句匹配一个值或一个模式,如果匹配成功,执行相匹配的命令。case语句格式如下:
case 值 in
模式1)
    command1
    command2
    command3
    ;;
模式2)
    command1
    command2
    command3
    ;;
*)
    command1
    command2
    command3
    ;;
esac

取值后面必须为关键字 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。;; 与其他语言中的 break 类似,意思是跳到整个 case 语句的最后。取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。

[root@master shell]# vi case

#!/bin/sh
echo 'Input a number between 1 to 4'
echo 'Your number is:\c'
read aNum
case $aNum in
    1)  echo 'You select 1'
    ;;
    2)  echo 'You select 2'
    ;;
    3)  echo 'You select 3'
    ;;
    4)  echo 'You select 4'
    ;;
    *)  echo 'You do not select a number between 1 to 4'
    ;;
esac
[root@master shell]# sh case

Input a number between 1 to 4
Your number is:\c
2
You select 2

9、循环

[root@master shell]# vi loop

#!/bin/sh
#for循环
for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done
#while循环
i=0
while [ $i -lt 4 ]
do
    i=`expr $i + 1`
    echo $i
done
#until循环
a=0
until [ ! $a -lt 4 ]
do
    echo $a
    a=`expr $a + 1`
done
[root@master shell]# sh loop
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
1
2
3
4
0
1
2
3

例:素数判定

[root@master shell]# vi prime

#!/bin/bash
n=$1
i=2
while ((i<=n/2));do
   if ((n%i==0));then
      break
   fi
   let i++
done
if ((i>n/2));then
   echo 'true'
else
   echo 'false'
fi

[root@master shell]# sh prime 10
false
[root@master shell]# sh prime 19
true

例:求10以内的素数

[root@master shell]# vi break

#!/bin/bash
i=2
while ((i<=10));do
    j=2
    while ((j<=i/2));do
       if ((i%j==0));then
           break
       fi
       let j++
    done
    if ((j>i/2));then
        echo $i
    fi
    let i++
done
[root@master shell]# sh  break
2
3
5
7

例:计算100以内非7倍数的整数和

[root@master shell]# vi continue 

#!/bin/bash
sum=0
i=0
while ((i<100));do
   let i++
   if ((i%7==0));then
      continue
   fi
   let sum=sum+i
done
echo $sum
[root@master shell]# sh continue 
4315

10、函数

也可以在函数名前加上关键字 function;函数返回值,可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。

Shell 函数返回值只能是整数,一般用来表示函数执行成功与否,0表示成功,其他值表示失败。如果 return 其他数据,比如一个字符串,往往会得到错误提示:“numeric argument required”。如果一定要让函数返回字符串,那么可以先定义一个变量,用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值。

调用函数只需要给出函数名,不需要加括号。

例:删除函数与函数返回值

[root@master shell]# vi fun1

#!/bin/bash
hi(){
  echo "hello"
}
hi
unset -f hi
hi
fun(){
  m=2
  n=3
  return $(($m+$n))
}
fun
rs=$?
echo $rs

[root@master shell]# sh fun1
hello
fun1: line 7: hi: command not found
5

例:参数

[root@master shell]# vi fun2

#!/bin/bash
fun(){
    echo "The value of the first parameter is $1 !"
    echo "The value of the second parameter is $2 !"
    echo "The value of the tenth parameter is $10 !"
    echo "The value of the tenth parameter is ${10} !"
    echo "The value of the eleventh parameter is ${11} !"
    echo "The amount of the parameters is $# !"  # 参数个数
    echo "The string of the parameters is $* !"  # 传递给函数的所有参数
}
fun 1 2 3 4 5 6 7 8 9 34 73

[root@master shell]# sh fun2
The value of the first parameter is 1 !
The value of the second parameter is 2 !
The value of the tenth parameter is 10 !
The value of the tenth parameter is 34 !
The value of the eleventh parameter is 73 !
The amount of the parameters is 11 !
The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !

注意,$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。


11、输入输出重定向

Unix 命令默认从标准输入设备(stdin)获取输入,将结果输出到标准输出设备(stdout)显示。一般情况下,标准输入设备就是键盘,标准输出设备就是终端,即显示器。

一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:
标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据。
标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据。
标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息

默认情况下,

1)command > file 将 stdout 重定向到 file

2)command < file 将stdin 重定向到 file

3)command &> file 全部重定向到file

如果希望 stderr 重定向到 file,可以这样写:
$command 2 > file

如果希望 stderr 追加到 file 文件末尾,可以这样写:
$command 2 >> file
2 表示标准错误文件(stderr)。

数据黑洞:

如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 /dev/null


12、Shell文件包含

像其他语言一样,Shell 也可以包含外部脚本,将外部脚本的内容合并到当前脚本。

Shell 中包含脚本可以使用:
. filename

source filename
两种方式的效果相同,简单起见,一般使用点号(.),但是注意点号(.)和文件名中间有一空格。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值