unix shell学习笔记-C shell编程

本文详细介绍了Shell脚本的基础概念,包括如何选择合适的shell,授予执行权限,运行脚本,以及如何实现用户输入读取、算术运算、条件结构和循环命令等功能。此外,还讲解了内置命令的使用。通过实例代码,读者可以快速掌握Shell脚本的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 内置命令

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值