`
xitonga
  • 浏览: 594095 次
文章分类
社区版块
存档分类
最新评论

shell程序设计(3)

 
阅读更多

shell程序设计(3)

shell语法

函数

要定义一个shell函数,我们只需要简单地写出它的名字,然后是一对空括号,再把有关的语句放在一对花括号中,如下所示:

function_name(){

statements

}

实验:简单的函数

#!/bin/bash

foo(){

echo“Function foo is executing”

}

echo “script starting”

foo

echo “script ended”

exit 0;

输出:

script starting

Function foo is executing

script ended

当一个函数被调用时,脚本程序的位置参数$*、$@、$1、$2等会被替换为函数的参数。这也是你读取传递给函数的参数的办法。当函数执行完毕后,这些参数会恢复为它们先前的值。

可以使用local关键字在shell函数中声明局部变量,局部变量将局限在函数的作用范围内。

实验:从函数中返回一个值

脚本程序:

#!/bin/sh

yes_or_no(){

echo "IS your name $*?"

while true

do

echo -n "Enter yes or no:"

read x

case "$x" in

y | yes ) return 0;;

n | no ) return 1;;

* ) echo "Answer yes of no"

esac

done

}

echo "original parameters are $*"

if yes_or_no "$1"

then

echo "ho $1, nice name"

else

echo "Never mind"

fi

exit 0

执行与输出结果

root@ubuntu:/home/chen123/C++# ./a RickNeil

original parameters are Rick Neil

IS your name Rick?

Enter yes or no:yes

ho Rick, nice name

命令

break命令: 跳出for、while或until循环

:命令:空命令,相当于true的一个别名

continue命令: 使for、while或until循环跳到下一次循环继续执行

.命令:用来执行当前shell中的命令

echo命令:输出结尾带换行符的字符串

eval命令:允许对参数进行求值

exec命令:典型用法是将当前shell替换为一个不同的程序。第二中用法非常少见,就是修改当前文件描述符

exit n命令:使脚本程序退出码n结束运行。

export命令:将作为它参数的变量导出到子shell中,并使之在shell中有效。

expr命令:将它的参数当做一个表达式来求值

printf命令:格式化输出

return命令:使函数返回

set命令:为shell设置参数变量

shift命令:把所有参数变量左移一个位置,使$2编程$1,$3编程$2,一次类推。原来$1的值被丢弃。

trap命令:用于指定在接收到信号后将要采取的行动

unset命令:从环境中删除变量或函数

find命令

功能:查找文件

简单的例子:用find在本地机器上查找名为wish的文件

$ find/ -name wish –print

/usr/bin/wish

这个命令执行需要花很长的时间,如果linux挂载了一大块windows机器的文件系统,还会搜索挂载的目录。

可以使用-mount选项,告诉find命令不要搜索挂载的目录。

$find / -mount –name -wish –print

/usr/bin/wish

find命令的完整语法格式如下所示:

find [path][options][tests][actions]

grep命令

功能:在文件中搜索字符串

语法:

grep [options] PATTERN [FILES]

root@ubuntu:/home/chen123/C++# grep -chello hello.c

1

输出hello在hello.c中匹配行的数目

here文档

here文档以连续的小于号<<开始,紧跟着一个特殊的字符序列,该序列将在文档的结尾处再次出现。<<是shell的标签重定向符号,此时,它表示命令输入的是一个here文档。

例子:

#! /bin/sh

cat << !FUNKY!

hello

this is a here

document

!FUNKY!

执行与输出

root@ubuntu:/home/chen123/C++# ./b

hello

this is a here

document


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics