脚本

来源:互联网 发布:电子书语音阅读软件 编辑:程序博客网 时间:2024/05/22 07:49


1.bash基本概念

BASH = GNU Bourne-Again Shell,BASH 是 GNU 组织开发和推广的一个项目。
Bash脚本类似批处理,简单来讲就是把许多的指令集合在一起,并提供循环、条件、判断等重要功能,语法简单实用,用以编写程序,大大简化管理员的操作,并可以完成图形工具所无法实现的功能。

2.脚本的基本格式

1)基本格式
[root@server3 ~]# vim /mnt/test.sh

#!/bin/bash        ##运行环境标识
echo hello world        ##脚本内容

[root@server3 ~]# bash  -x /mnt/test.sh     ##预执行并检测是否有语法错误
+ echo hello world

hello world

2)脚本的执行必须加执行权限
[root@server3 ~]# chmod  +x /mnt/test.sh    ##给脚本文件加执行权限
[root@server3 ~]# /mnt/test.sh 
hello world

3)将脚本的文件放在$PATH的目录中(eg:/usr/bin)可在任何路径下直接执行该脚本命令
[root@server3 ~]# cp -p /mnt/test.sh /usr/bin/
[root@server3 ~]# test.sh          ##在系统的任何路径下均可执行
hello world

3.引用与转义

引用和转义在shell解析字符串时用于去除字符串中特殊字符或保留词语的特殊含义。
这会导致按字面处理字符串,而不是展开变量或将其部分内容视作具有特殊含义。

引用有三种类型:

1)弱引用
将字符串放置在双引号中,保留字符串中所有字符的文字值,$、`、\和!字符除外。换言之,变量扩展和命令扩展在双引号内仍起作用。
echo “can I have a $FRUIT”
[root@localhost mnt]# sh test.sh
can I have a
echo “The current time is $(date +%r).”

[root@localhost mnt]# sh test.sh
The current time is 07:43:24 AM.

2)强引用
将字符串放置在单引号中,保留字符串中所有字符的文字值,同时禁用所有扩展:
echo 'Make $$$ Fast'
[root@localhost mnt]# sh test.sh
Make $$$ Fast

rm 'untitled folder'


3)转义
非引用的\是转义字符。它保留了下一个字符的文字值。(例如,\$PATH是确切的字符串$PATH,而不是PATH变量的内容。)
echo Make \$\$\$ Fast\!
[root@localhost mnt]# sh test.sh
 Make $$$ Fast! 

ls untitled\ folder
3)转义
非引用的\是转义字符。它保留了下一个字符的文字值。(例如,\$PATH是确切的字符串$PATH,而不是PATH变量的内容。)
echo Make \$\$\$ Fast\!
[root@localhost mnt]# sh test.sh
 Make $$$ Fast! 

ls untitled\ folder

原创粉丝点击