简单的shell脚本

1.第一个 shell 脚本

#!/bin/bash
#This is my first shell script
date
who

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

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

#!/bin/bash
#dispaay user information from the system
echo "User info for userid: $USER"
echo UID :$UID
echo HOME:$HOME

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

#!/bin/bash
#testing varibles
days=10
guest="Katie"
echo "$guest checked in $days days ago"

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

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

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

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

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

#!/bin/bash
#Testing the if statement
if date
then echo "It worked"
fi

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

#!/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
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 命令

#!/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. 简单的文件的比较

检查文件的目录

#!/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 放在同一行,但是必须要使用分号来分割

for var in list ;do

范例:

  • 读取列表中的值
#!/bin/bash
#basic for command
for test in A B C
do
	echo the litter is $test
done
  • 从变量读取列表 通常 shell 脚本遇到的情况是你将一系列的值都集中存储在了一个变量中,然后需要遍历整个的列表:
#!/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 命令中使用该命令的输出:
#!/bin/bash
#reading values from a file
file="states"
for state in `cat $file`
do
	echo $state
done