linux 脚本(bash script)技巧

本文介绍10个小技巧。

1 使用注释
写注释有助于你和其他人理解你的脚本

#!/bin/bash
#Linux is the best OS.

2 设置脚本遇错误就退出
一些脚本会一直执行下去,就算遇到确定的错误。为了避免,我们需要做些设置。

#!/bin/bash
#let script exit if a command fails
set -o errexit 
OR
set -e

3 检测脚本使用没有申明的变量时,脚本自动退出

#!/bin/bash
#let script exit if an unsed variable is used
set -o nounset
OR
set -u

4 用双引号来引用变量
用双引号来声明变量可以避免,空格符 和 匹配符造成的歧义

#!/bin/bash
#let script exit if a command fails
set -o errexit 

#let script exit if an unsed variable is used
set -o nounset

echo "Names without double quotes" 
echo
names="Linxmint FOSSMint Linusay"
for name in $names; do
        echo "$name"
done
echo

echo "Names with double quotes" 
echo
for name in "$names"; do
        echo "$name"
done

exit 0

运行后

Names without double quotes

Linxmint
FOSSMint
Linusay

Names with double quotes

Linxmint FOSSMint Linusay

5 在脚本中使用函数
大的脚本,推荐用函数,可以优化你的代码,以及更好的理解代码。

#!/bin/bash
function check_root(){
	command1; 
	command2;
}

OR
check_root(){
	command1; 
	command2;
}

6 用 =代替 == 做比较
这两个符号意义相同

value1=”linuxmint.com”
value2=”fossmint.com”
if [ "$value1" = "$value2" ]

7 用$(command)替代command 的命令输出

user=`echo “$UID”`
user=$(echo “$UID”)

$(command) 看上去更直观。

8 使用只读来声明静态变量

readonly passwd_file=”/etc/passwd”
readonly group_file=”/etc/group”

9 用 大写字母申明环境变量,用小写字母声明客户变量

#define custom variables using lowercase and use uppercase for env variables
nikto_file=”$HOME/Downloads/nikto-master/program/nikto.pl”
perl “$nikto_file” -h  “$1”

10 调试长代码脚本
如果你的脚本有长达百行,千行代码,记得要调试。

#!/bin/sh option(s) scriptname arg1 arg2 arg3 .....
-v(verbose)   -n (no excution)  -x (excutions)

猜你喜欢

转载自blog.csdn.net/CSDN1887/article/details/86132955
今日推荐