shell 编程(一)
看例子,习惯下吧!

#!/bin/bash
#eg1 清除系统日志文件的脚本
cd /var/log
cat /dev/null > messages
echo "logs cleaned up!"
[root@bogon shell]# sh test1.sh
logs cleaned up!
[root@bogon shell]# cat /var/log/messages
[root@bogon shell]#
1 #!/bin/bash
2 #eg2 包含命令/变量和流程控制语句的清除/var/log下的messages日志文件的shell脚本
3 LOG_DIR=/var/log
4 ROOT_UID=0
5 if [ "$UID" -ne "$ROOT_UID" ]
6 then
7 echo "must be root to run this script!"
8 exit 1
9 fi
10 cd $LOG_DIR || {
11 echo "cannot change to necessary directory" >&2
12 exit 1
13 }
14 cat /dev/null > messages
15 echo "logs cleaned up!"
[root@bogon shell]# sh test2.sh
logs cleaned up!
[root@bogon shell]# cat /var/log/messages
[root@bogon shell]#
[root@bogon shell]# echo $SHELL
/bin/bash
[root@bogon shell]# ll /bin/sh
lrwxrwxrwx. 1 root root 4 6月 17 17:54 /bin/sh -> bash
//bash几种执行方式
[root@bogon shell]# ll test1.sh
-rw-r--r--. 1 root root 114 7月 11 21:10 test1.sh
[root@bogon shell]# bash test1.sh
logs cleaned up!
[root@bogon shell]# sh test1.sh
logs cleaned up!
[root@bogon shell]# path/test1.sh
bash: path/test1.sh: 没有那个文件或目录
[root@bogon shell]# ./test1.sh
bash: ./test1.sh: 权限不够
[root@bogon shell]# source test1.sh
logs cleaned up!
[root@bogon shell]# . test1.sh
logs cleaned up!
[root@bogon log]#
[root@bogon shell]# chmod u+x test.sh
[root@bogon shell]# ./test.sh
i am a boy
//内容较少时可如下编辑,ctrl+D 结束
[root@bogon shell]# cat > test.sh
echo "i am a boy"
[root@bogon shell]# cat test.sh
echo "i am a boy"
[root@bogon shell]# sh test.sh
i am a boy
[root@bogon shell]#
//实验结论:通过source或者. 加载执行脚本,在脚本结束后脚本中的变量(包括函数)值在当前shell中依然存在,而sh和bash则不行。
[root@bogon shell]# echo 'userdir=`pwd`' > testsource.sh
[root@bogon shell]# cat testsource.sh
userdir=`pwd`
[root@bogon shell]# sh testsource.sh
[root@bogon shell]# echo $userdir
[root@bogon shell]# //执行后为空
[root@bogon shell]# source testsource.sh
[root@bogon shell]# echo $userdir
/root/shell //出现结果!
[root@bogon shell]#
PS:好的习惯可以让我们避免很多不必要的麻烦,提升很多的效率!
学习核心:重思路、重方法、重实践、重习惯、重总结。
浙公网安备 33010602011771号