Shell文件起始语句:#!/bin/bash或者#!/bin/sh
例如:
#! /bin/sh
#out a
a = “hello world” 定义变量a 赋予语句”hello world”
Echo ${a} echo 输出后面变量信息
默认变量:
$#:输入脚本的命令行参数个数
$*:所有命令行参数值
$0:命令本身(shell文件名)
&1:第一个命令行参数
$2:第二个命令行参数
入参判断:
if [ $# -ne 3 ] ; then if判断后面的方括号内侧都要空格;判断命令行参数个数是否=3
( -eq ) -ne:不等于;-eq等于
...
...
fi fi表示if判断结束
整体实例:(先输出一句话,然后对比参数个数,=3时做do,!=3时告知正确输入格式)
#! /bin/sh
Echo “my name is tom”
If [ $# -ne 3 ] ; then
Echo “the way is $0 dirname1 dirname2 dirname3”
Exit 1
Elif [ $# -eq 3 ] ; then
Echo $1
Echo $2
Echo $3
Echo $*
Fi
For dir in $1 $2 $3
Do
Mkdir ${dir} (创建和参数名相同的文件夹)
Cd ${dir} (进入该文件夹)
Touch ${dir}.txt (创建同名txt文件)
Echo “my name is tom” > ${dir}.txt (向同名txt文件内输入my name is tom)
Cd .. (返回上一层目录)
Done
执行脚本文件:(查看结果)
[[email protected] 1013]# ./test.sh
my name is tom
the way is :./test.sh dirname1 dirname2 dirname3
[[email protected] 1013]# ./test.sh a b c
my name is tom
a
b
c
a b c
[[email protected] 1013]# ls
a b c test.sh
[[email protected] 1013]# cd a
[[email protected] a]# ls
a.txt
[[email protected] a]# cat a.txt
my name is tom
其余判断:
-r: 判断是否为文件夹
-f: 判断是否为文件
Case: 类似switch语句做判断, ;;相当于break
例1:
#! /bin/sh
Folder=/home
[ -r “$folder” ] && echo “can read $folder”
[ -f “$folder” ] || echo “this is not a file”
执行脚本:
[[email protected] 1013]# ./file.sh
can read /home
this is not a file
例2:
#! /bin/sh
Read key
Case ${key} in
[A-Z] ) echo “uppercase letter”;;
[a-z] ) echo “lowercase letter”;;
[0-9] ) echo “number”;;
* ) echo “unkown”;;
Esac
执行脚本:
[[email protected] 1013]# chmod 777 case.sh
[[email protected] 1013]# ./case.sh
A
uppercase letter
[[email protected] 1013]# ./case.sh
a
lowercase letter
[[email protected] 1013]# ./case.sh
1
Number
[[email protected] 1013]# ./case.sh
!
unkown