Shell脚本编程30分钟入门(小结)

2019-09-23 08:52:25于丽

C风格的for

for (( EXP1; EXP2; EXP3 ))

do

    command1

    command2

    command3

done

while

while condition

do

    command

done

无限循环

while :

do

    command

done

或者

while true

do

    command

done

或者

for (( ; ; ))

until

until condition

do

    command

done

case

case "${opt}" in

    "Install-Puppet-Server" )

        install_master $1

        exit

    ;;

 

    "Install-Puppet-Client" )

        install_client $1

        exit

    ;;

 

    "Config-Puppet-Server" )

        config_puppet_master

        exit

    ;;

 

    "Config-Puppet-Client" )

        config_puppet_client

        exit

    ;;

 

    "Exit" )

        exit

    ;;

 

    * ) echo "Bad option, please choose again"

esac

case的语法和C family语言差别很大,它需要一个esac(就是case反过来)作为结束标记,每个case分支用右圆括号,用两个分号表示break

函数

定义

调用

文件包含

可以使用source和.关键字,如:

source ./function.sh

. ./function.sh

在bash里,source和.是等效的,他们都是读入function.sh的内容并执行其内容(类似PHP里的include),为了更好的可移植性,推荐使用第二种写法。

包含一个文件和执行一个文件一样,也要写这个文件的路径,不能光写文件名,比如上述例子中:

. ./function.sh

不可以写作:

. function.sh

如果function.sh是用户传入的参数,如何获得它的绝对路径呢?方法是:

real_path=`readlink -f $1`#$1是用户输入的参数,如function.sh

. $real_path

用户输入

执行脚本时传入

脚本运行中输入

select菜单

stdin和stdout

常用的命令

sh脚本结合系统命令便有了强大的威力,在字符处理领域,有grep、awk、sed三剑客,grep负责找出特定的行,awk能将行拆分成多个字段,sed则可以实现更新插入删除等写操作。

ps

查看进程列表

grep

排除grep自身

查找与target相邻的结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。