1.第一个shell脚本

1
2
3
4
#!/bin/bash
#This is my first shell script
date
who

这是我们的第一个shell脚本,它的功能是打印系统的当前时间和当前用户,我们使用#号来表示注释。但是shell脚本的第一行是一个例外,#!告诉shell用哪个shell来运行脚本,此处我们是使用bash shell

2.编写一个脚本来获取当前用户环境变量

1
2
3
4
5
6
#!/bin/bash
#dispaay user information from the system
echo "User info for userid: $USER"
echo UID :$UID
echo HOME:$HOME

3. 编写一个脚本来使用用户变量

1
2
3
4
5
#!/bin/bash
#testing varibles
days=10
guest="Katie"
echo "$guest checked in $days days ago"

4.脚本中的反引号的使用

反引号中的内容表示命令本身,反引号允许你将shell命令的输出复制给变量。

1
2
3
4
#!/bin/bash
#using the backtick character
testing=`date`
echo "The date and time are:" $testing
1
2
3
#!/bin/bash 
today=`date +%y%m%d
ls /usr/bin -al > log.$today

5.脚本中结构化命令的使用

使用if- then语句 基本的格式是 if command then command fi

1
2
3
4
5
#!/bin/bash
#Testing the if statement
if date
then echo "It worked"
fi

另一种格式 if command then command else command fi

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash
#test the else section
testuser=aaaaa
if grep $testuser /etc/passwd
then
	echo The files for user $testuser are:
	ls -a /home/$testuser/.b*
else 
	echo "The user $testuser does not exist on this system"
fi
1
2
3
4
5
6
7
if command1
then command2
elif connand3
then command4
.
.
.

if **[ ]**中的一些判断条件

  1. 字符的判断
  • string1 = string2 字符串相等
  • string1 != string2 字符串不相等
  • -n string1 字符串长度大于零
  • -z string1 字符串长度等于0
  • string1 字符串非空
  1. 数字的判断
  • -eq 相等
  • -ne 不相等
  • -gt 大于
  • -ge 大于等于
  • -lt 小于
  • -le 小于等于
  1. 文件的判断
  • -r 用户可读
  • -w 用户可写
  • -x 用户可执行
  • -f 文件为普通文件
  • -d 文件为一个目录
  • -c 文件为字符特殊文件
  • -b 文件为块特殊文件
  • -s 文件大小非零
  1. 逻辑判断
  • -a
  • -o
  • !

6. test命令

1
2
3
4
5
6
7
8
9
#!/bin/bash
#using numeric test comparisons
var1=10
var2=11
if [ %var1 -gt %var2 ]
then 
	echo "%var1 is greater than %var2"
else 
	echo "%var1 is smaller than %var2"

7. 简单的文件的比较

检查文件的目录

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash
#look before you leap
if [-d $HOME]
then
	echo "your home directory exist"
	cd $HOME
	ls -a
else 
	echo "There is a problem with your HOME directory"
fi

8. 脚本中的循环

重复执行一系列命令在编程中是很常见的。bash shell 提供了for命令,允许你建立一个遍历一系列值的循环,典型的应用是

for var in list
do
	commands
done

在do和done语句之间输入的命令可以是一条或者多条的标准的shell命令 也可以把do和for放在同一行,但是必须要使用分号来分割

1
for var in list ;do

范例:

  • 读取列表中的值
1
2
3
4
5
6
7
#!/bin/bash
#basic for command
for test in A B C 
do
	echo the litter is $test
done

  • 从变量读取列表 通常shell脚本遇到的情况是你将一系列的值都集中存储在了一个变量中,然后需要遍历整个的列表:
1
2
3
4
5
6
7
8
#!/bin/bash
#using a variable to hold the list 
list ="A B C D"
list=$list" R"
for letter in list
do
	echo $letter
done
  • 从命令读取值 生成列表中要用到的值的另外一个途径就是使用命令的输出。你可以使用反引号来执行任何能产生输出命令的命令,然后再for命令中使用该命令的输出:
1
2
3
4
5
6
7
#!/bin/bash
#reading values from a file
file="states"
for state in `cat $file`
do
	echo $state
done