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