shell脚本基础

shell定义:

Shell是命令解析器,将用户的输入的指令转化为机器可以运行的程序。

和c语言不同,脚本有自己的语法。

比较常用的格式是:#!/bin/bash或者#!/bin/sh

如:

这是一个判断输入字符类型的程序

#!/bin/bash
read key
case "${key}" in
[A-Z]) echo "upperletter";;
[a-z]) echo "lowerletter";;
[0-9]) echo "number";;
*) echo "error";;
esac

终端

[root@localhost C]# ./case.sh 
t
upperletter

如:

#!/bin/bash
Tmp="hello"
#echo="helloworld"
#echo $Tmp


#echo $1       ($1$2对应终端./文件名.sh后面的参量)
#echo $2        (echo作为输出函数)
#echo $3
#echo $*         (所有参数输入)
#echo $#
for dir in $1 $2 $3 $4 $5  (dir依次等于$1$2等)
do
mkdir $dir                 (创建一个dir对应参量的目录)

cd $dir                      (进入目录)

touch $dir                  (创建dir对应参量同名的文件)
echo "hello $dir">$dir  (将hello赋给dir)

cd ..                    (退出目录)
done                  (结束)

终端输入:

[root@localhost C]# ./shell.sh  11 22
[root@localhost C]# ls
11  a1     Author:  const.c  hello    hello.sh  if.c      moshou    pash     quyu    scanf.c   sizeof    strlen    strlen.c.c  switch.c
22  a.out  case.sh  File     hello.c  if        jisuan.c  moshou.c  pash.sh  quyu.c  shell.sh  sizeof.c  strlen.c  switch


[root@localhost 22]# ./22
bash: ./22: 权限不够
[root@localhost 22]# chmod 777 22
[root@localhost 22]# cat 22 (显示文件22中的内容)
hello 22 (说明hello添加成功)

 

 


例:

#!/bin/bash
PATH=$1
if [ -z $PATH ]; then      (判断是否为空)
echo "ERROR"
exit                     (退出程序)
fi
if [ -d $PATH ]; then        (判断是否为一个目录)
echo "DIR"
elif [ -f $PATH ]; then       (判断是否为一个文件)
echo "file"
fi

在终端输入:

[root@localhost C]# ls
11  a1     Author:  const.c  hello    hello.sh  if.c      moshou    pash     quyu    scanf.c   sizeof    strlen    strlen.c.c  switch.c
22  a.out  case.sh  File     hello.c  if        jisuan.c  moshou.c  pash.sh  quyu.c  shell.sh  sizeof.c  strlen.c  switch
[root@localhost C]# ./pash.sh if     (判断if的属性)
file

 

例:用脚本写c语言程序

#!/bin/bash
file="hello.c"
target="hello"
#echo "#include <stdio.h>" >$file    (#在脚本里起到注释作用)
#echo "int main()" >>$file
#echo "{" >>$file
#echo ' printf("helloword!\n");'>>$file
#echo  "}" >>$file
cat > $file <<EOF
#include <stdio.h>
int main()
{
printf("helloworld\n";)
return 0;
}
gcc $file -o $target
./$target

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值