`

unix shell学习笔记-C shell编程

 
阅读更多

6.1 简介

Shell脚本由命令和散布其间的注释组成。

 创建运行脚本的步骤

运行脚本步骤为:

选择shell

授予执行权限

执行脚本

 

 

 

选择shell,第一行以#!即shbang指明所用的shell解释器,如:

 

#!/bin/csh 或者#!/bin/tcsh

 

授予执行权限:

 

% chmod +x myscript

 

运行脚本:

 

% ./myscript 

 

 


6.2 读取用户输入

例子:

通过变量$<读取用户输入。

 

#!/bin/csh -f 
echo -n "What is your name? " 
set name = $< 
echo Greeting to you, $name. 

 

6.3 算术运算

C shell只支持整数的算术运算

算术运算符:+ - / * % << >>

快捷运算符:+= -= *= /= ++ --

 

6.4 条件结构和流控制

if语句:

if (expression)

    command

    command

then

    command

    command

endif

例:

 

if ($#argv != 1 ) then 
    echo "$0 requires an argument" 
    exit 1 
endif 

#说明:如果命令行传入的参数个数($#argv)不等于1,则执行then后面的语句 
# 程序以值1退出,表示运行失败 

 

if/else语句

格式:

if (expression) then

    command

else

    command

endif 

 

if/else if 语句

 

格式:

 

if (expression) then

    command

    command

else if (expression) then

    command

    command

else

    command

endif

 

退出状态和变量status

 

执行成功:$status = 0

执行失败:$status != 0

 

switch语句

格式:

 

switch (var)

case Const1:

    command

    breaksw

case Const2:

    command

    breaksw

endsw

 #! /bin/csh 
echo "Select from the following menu:" 
cat << EOF 
1) Red 
2) Green 
3) Blue 
4) Exit 
EOF 
set choice = $< 
switch ("$choice") 
case 1: 
    echo Red is stop. 
    breaksw 
case 2: 
    echo Green is go\! 
    breaksw 
case 3: 
    echo Blue is a feeling... 
    breaksw 
case 4: 
    exit 
    breaksw 
default: 
    echo Not choice \!\! 
endsw 
echo Good-bye 

 

 

6.5 循环命令

 

 foreach循环

格式:

foreach 变量

command

end

 

例:

 

foreach person (Rob Bob Tim Jim)

    echo $person

end

 

 


while循环

 


格式:

 


while ()

 


end 

 


repeat循环

repeat 3 echo hello

 


hello

hello

hello   

6.6 内置命令

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics