shell脚本,shell语法和结构(以Cshell/TC shell为例)
阅读原文时间:2023年07月08日阅读:1

1.C shell/TC shell常用语法和结构

(1) shbang行: #!/bin/sh,通知内核使用哪种内核解释脚本;

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

(2) 注释: 以#开头;

#This is a comment

(3) 通配符: *等;

(4) 显示输出: echo “***”;

echo "Hello!"

(5) 局部变量设置: set variable_name=value;

set name="Tom"

(6) 全局变量设置: setenv VARIABLE_NAME value;

setenv PRINTER shakespeare

(7) 提取变量值: echo $variable_name;

echo $anme
echo $PRINTER

(8) 读取用户输入:通过$<从用户输入中读取一行并将其赋给一个变量,如set name=$<;

echo "What's your name?"
set name=$<

(9) 脚本命令行参数: scriptname arg1 arg2 arg3 …,其中arg1,arg2,arg3…将依次赋给$1,$2,$3…(或者$argv[1], $argv[2], $argv[3]…);使用echo $*(或echo $argv[*])可以显示所有命令行参数;

scriptname arg1 arg2 arg3 …
echo $1 $2 $3
echo $*
echo $argv[1] $argv[2] $argv[3]
echo $argv[*]

(10) 数组:用空格隔开的一系列词组成的词表,由一对圆括号括起来; 注意,使用索引访问数组中的某个单词,索引值从1开始,而不是从0开始;

set word_list = (word1 word2 word3)
set names = (Tom Harry)
shift names
echo $word_list[1]
echo $word_list[2]
echo $word_list or echo $word_list[*]

(11) 算术运算: 保存算数运算结果的变量必须以一个@符号加一个空格开头;

@ n = 5+5
echo $n

注1:符号@后面以及运算符两侧都必须有空格;

(12) 条件语句(if结构与switch结构)

#if结构
if(expression) then
block of statements
endif

#if/else结构
if(expression) then
block of statements
else
block of statements
endif

#if/else if/else结构
if(expression) then
block of statements
else if(expression) then
block of statements
else if(expression) then
block of statements
else
block of statements
endif

switch (variable_name)
case constant1:
statements
case constant2:
statements
case constant3:
statements
default:
statements
endsw

(13) 循环语句(while循环与foreach循环)

while(expression)
block of statements
end

foreach variable (word list)
block of statements
end

(14) 文件测试

-r 当前用户可以读该文件
-w 当前用户可以写该文件
-x 当前用户可以执行该文件
-e 该文件存在
-o 该文件属于当前用户
-z 该文件长度为0
-d 该文件是一个目录
-f 该文件是一个普通文件

2.C shell/TC shell示例(比较有趣,可以发送邮件)

#!/bin/csh #如果该句末尾加上-f,则表示不要执行.cshrc文件;通常情况下,每当一个新的csh程序启动时,会自动执行一个初始化文件;

The party program-invitations to friends from the "guest" file

set guestfile=~/guests
if( ! -e "$guestfile") then
echo "$guestfile:t non-existent" #注意,:t比较有意思,如果不添加,会显示guestfile的完整名字,如果添加,则只显示guests;
exit 1
endif

setenv PLACE "Sarotini's"
@ Time='date +%H' + 1

set food=( cheese crackers drinks "hot dogs" )

foreach person (`cat $guestfile`)
if( $person =~ root ) continue
mail -v -s "Parity" $person <<FINIS #start of here document
Hi $person! Please join me at $PLACE for party!
Meet me at $Time o'clock.
I'll bring the ice cream. Would you please bring $food[1] and
anything else you would like to eat? Let me know if you can
make it. Hope to see you soon.
Your pal,
ellie@`hostname`
FINIS
shift food
if( $#food ==0 ) then
set food=( cheese crackers drinks "hot dogs" )
endif
end