Shell脚本学习第二课·

Shell文件包含

shell也可以包含外部脚本,语法格式如下:

. filename

source filename

例如创建两个shell脚本。

脚本1:test1.sh

url = "www.baidu.com"

脚本2:test2.sh

. ./test1.sh

echo "$url"

执行test2.sh,即可看到结果。

Shell输入输出重定向

命令 说明
command>file 将输出重定向到file
command<file 将输入重定向到file
command>>file 将输出以追加的方式重定向到file
n>file 将文件描述符为n的文件重定向到file
n>>file 将文件描述符为n的文件以追加的方式重定向到file
n>&m 将输出文件m和n合并
n<&m 将输入文件m和n合并
<<tag 将开始标记tag和结束tag之间的内容作为输入

 

 

 

 

 

 

 

注意:文件描述符0通常是标准输入(STDIN),1是标准输出(STDOUT),2是标准错误输出(STDERR)

重定向深入讲解

一般情况下,每个Unix/Linux命令运行时都会打开三个文件:

  • 标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据。
  • 标准输出文件(stdout):stdout的文件描述符为1,Unix程序默认向stdout输出数据
  • 标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息。

默认情况下,command>file将stdout重定向到file,command<file将stdin重定向到file。

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

command 2>file  #2表示标准错误文件

command 2>>file  #追加 2表示标准错误文件

如果希望将stdout和stderr合并后重定向到file,可以这样写

command > file 2>&1

command >> file 2>&1 

Shell函数

格式

[function] funname [()]

{

  action;

  [return int;]  #return后跟数值n(0-255)

}

例子

demoFun(){

  echo "这是我的第一个shell函数"

}

echo "--start--"

demoFun

echo "--end--"

例子:带有return

funWithRetun(){

  echo "输入第一个数字"

  return aNum

  echo "输入第二个数字"

  return bNum

  return $(($aNum+$bNum))

}

funWithReturn

echo "输入的两个数字之和为$?"  #函数返回值在调用该函数后通过$?来获得

例子:函数参数

funWithParam(){

  echo "第一个参数为$1"  #$1表示第一个参数,$2表示第二个参数,获取大于等于10个参数需用${n}

  echo "第五个参数为$5"

  echo "第十个参数为${10}"

  echo "第十四个参数为${14}"

  echo "所有参数$*"

}

funWithParam 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

参数处理 说明
$# 传递到脚本的参数个数
$* 以一个单字符串显示所有向脚本传递的参数
$$ 脚本运行的当前进程ID号
$! 后台运行的最后一个进程的ID号
$@ 与$*相同,但是使用时加引号,并在引号中返回每个参数
$- 显示shell使用的当前选项,与Set命令功能相同
$? 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误

 

 

 

 

 

 

Shell流程控制

if else

格式:

if condition

then

  command1

  command2

fi

if else-if else

格式

if condition1

then

  command1

elif condition2

then

  command2

else

  commandN

fi

for循环

格式

for var in item1 item2 ... itemN

do

  command1

...

  commandN

done

例子

for loop in 1 2 3 4 5

do

  echo "the value is : $loop"

done

while

格式

while condition

do

  command

done

例子

int=1

while(($int<=5))

do

  echo $int

  let "int++"

done

无限循环

while :

do

  command

done

 

while true

do

  command

done

until循环

until condition

do

  command

done

case

case 值 in

模式1)

  command1

  command2

  ...

  commandN

  ;;

模式2)  

  command1

  command2

  ...

  commandN

  ;;

esac

跳出循环

break

continue

 

posted @ 2016-12-16 02:45  初级编程  阅读(189)  评论(0编辑  收藏  举报