linux shell整蛊代码,让代码整洁、过程清晰的BASH Shell编程技巧
这是我写BASH程序的招式。这里本没有什么新的内容,但是从我的经验来看,人们爱滥用BASH。他们忽略了计算机科学,而从他们的程序中创造的是“大泥球”(译注:指架构不清晰的软件系统)。
在此我告诉你方法,以保护你的程序免于障碍,并保持代码的整洁。
一、不可改变的全局变量
1.尽量少用全局变量
2.以大写命名
3.只读声明
4.用全局变量来代替隐晦的$0,$1等
在我的程序中常使用的全局变量:
readonly PROGNAME=$(basename $0)
readonly PROGDIR=$(readlink -m $(dirname $0))
readonly ARGS="$@"
二、一切皆是局部的
所有变量都应为局部的。
change_owner_of_file() {
local filename=$1
local user=$2
local group=$3
chown $user:$group $filename
}
change_owner_of_files() {
local user=$1; shift
local group=$1; shift
local files=$@
local i
for i in $files
do
chown $user:$group $i
done
}
1.自注释(self documenting)的参数
2.通常作为循环用的变量i,把它声明为局部变量是很重要的。
3.局部变量不作用于全局域。
kfir@goofy ~ $ local a
bash: local: can only be used in a function
三、main()
1.有助于保持所有变量的局部性
2.直观的函数式编程
3.代码中唯一的全局命令是:main
main() {
local files="/tmp/a /tmp/b"
local i
for i in $files
do
change_owner_of_file kfir users $i
done
}
main
四、一切皆是函数
唯一全局性运行的代码是:
- 不可变的全局变量声明
- main()函数
1.保持代码整洁
2.过程变得清晰
main() {
local files=$(ls /tmp | grep pid | grep -v daemon)
}
temporary_files() {
local dir=$1
ls $dir \
| grep pid \
| grep -v daemon
}
main() {
local files=$(temporary_files /tmp)
}
1.第二个例子好得多。查找文件是temporary_files()的问题而非main()的。这段代码用temporary_files()的单元测试也是可测试的。
2.如果你一定要尝试第一个例子,你会得到查找临时文件以和main算法的大杂烩。
test_temporary_files() {
local dir=/tmp
touch $dir/a-pid1232.tmp
touch $dir/a-pid1232-daemon.tmp
returns "$dir/a-pid1232.tmp" temporary_files $dir
touch $dir/b-pid1534.tmp
returns "$dir/a-pid1232.tmp $dir/b-pid1534.tmp" temporary_files $dir
}
如你所见,这个测试不关心main()。
五、调试函数
带-x标志运行程序:
bash -x my_prog.sh
只调试一小段代码,使用set-x和set+x,会只对被set -x和set +x包含的当前代码打印调试信息。
temporary_files() {
local dir=$1
set -x
ls $dir \
| grep pid \
| grep -v daemon
set +x
}
打印函数名和它的参数:
temporary_files() {
echo $FUNCNAME $@
local dir=$1
ls $dir \
| grep pid \
| grep -v daemon
}
调用函数:
temporary_files /tmp
会打印到标准输出:
temporary_files /tmp
六、代码的清晰度
这段代码做了什么?
main() {
local dir=/tmp
[[ -z $dir ]] \
&& do_something...
[[ -n $dir ]] \
&& do_something...
[[ -f $dir ]] \
&& do_something...
[[ -d $dir ]] \
&& do_something...
}
main
让你的代码说话:
is_empty() {
local var=$1
[[ -z $var ]]
}
is_not_empty() {
local var=$1
[[ -n $var ]]
}
is_file() {
local file=$1
[[ -f $file ]]
}
is_dir() {
local dir=$1
[[ -d $dir ]]
}
main() {
local dir=/tmp
is_empty $dir \
&& do_something...
is_not_empty $dir \
&& do_something...
is_file $dir \
&& do_something...
is_dir $dir \
&& do_something...
}
main
七、每一行只做一件事
用反斜杠\来作分隔符。例如:
temporary_files() {
local dir=$1
ls $dir | grep pid | grep -v daemon
}
可以写得简洁得多:
temporary_files() {
local dir=$1
ls $dir \
| grep pid \
| grep -v daemon
}
符号在缩进行的开始
符号在行末的坏例子:(译注:原文在此例中用了temporary_files()代码段,疑似是贴错了。结合上下文,应为print_dir_if_not_empty())
print_dir_if_not_empty() {
local dir=$1
is_empty $dir && \
echo "dir is empty" || \
echo "dir=$dir"
}
好的例子:我们可以清晰看到行和连接符号之间的联系。
print_dir_if_not_empty() {
local dir=$1
is_empty $dir \
&& echo "dir is empty" \
|| echo "dir=$dir"
}
八、打印用法
不要这样做:
echo "this prog does:..."
echo "flags:"
echo "-h print help"
它应该是个函数:
usage() {
echo "this prog does:..."
echo "flags:"
echo "-h print help"
}
echo在每一行重复。因此我们得到了这个文档:
usage() {
cat <
usage: $PROGNAME options
Program deletes files from filesystems to release space.
It gets config file that define fileystem paths to work on, and whitelist rules to
keep certain files.
OPTIONS:
-c --config configuration file containing the rules. use --help-config to see the syntax.
-n --pretend do not really delete, just how what you are going to do.
-t --test run unit test to check the program
-v --verbose Verbose. You can specify more then one -v to have more verbose
-x --debug debug
-h --help show this help
--help-config configuration help
Examples:
Run all tests:
$PROGNAME --test all
Run specific test:
$PROGNAME --test test_string.sh
Run:
$PROGNAME --config /path/to/config/$PROGNAME.conf
Just show what you are going to do:
$PROGNAME -vn -c /path/to/config/$PROGNAME.conf
EOF
}
注意在每一行的行首应该有一个真正的制表符‘\t'。
在vim里,如果你的tab是4个空格,你可以用这个替换命令:
:s/^ /\t/
九、命令行参数
这里是一个例子,完成了上面usage函数的用法。我从http://kirk.webfinish.com/2009/10/bash-shell-script-to-use-getopts-with-gnu-style-long-positional-parameters/ 得到这段代码
cmdline() {
# got this idea from here:
# http://kirk.webfinish.com/2009/10/bash-shell-script-to-use-getopts-with-gnu-style-long-positional-parameters/
local arg=
for arg
do
local delim=""
case "$arg" in
#translate --gnu-long-options to -g (short options)
--config) args="${args}-c ";;
--pretend) args="${args}-n ";;
--test) args="${args}-t ";;
--help-config) usage_config && exit 0;;
--help) args="${args}-h ";;
--verbose) args="${args}-v ";;
--debug) args="${args}-x ";;
#pass through anything else
*) [[ "${arg:0:1}" == "-" ]] || delim="\""
args="${args}${delim}${arg}${delim} ";;
esac
done
#Reset the positional parameters to the short options
eval set -- $args
while getopts "nvhxt:c:" OPTION
do
case $OPTION in
v)
readonly VERBOSE=1
;;
h)
usage
exit 0
;;
x)
readonly DEBUG='-x'
set -x
;;
t)
RUN_TESTS=$OPTARG
verbose VINFO "Running tests"
;;
c)
readonly CONFIG_FILE=$OPTARG
;;
n)
readonly PRETEND=1
;;
esac
done
if [[ $recursive_testing || -z $RUN_TESTS ]]; then
[[ ! -f $CONFIG_FILE ]] \
&& eexit "You must provide --config file"
fi
return 0
}
你像这样,使用我们在头上定义的不可变的ARGS变量:
main() {
cmdline $ARGS
}
main
十、单元测试
1.在更高级的语言中很重要。
2.使用shunit2做单元测试
test_config_line_paths() {
local s='partition cpm-all, 80-90,'
returns "/a" "config_line_paths '$s /a, '"
returns "/a /b/c" "config_line_paths '$s /a:/b/c, '"
returns "/a /b /c" "config_line_paths '$s /a : /b : /c, '"
}
config_line_paths() {
local partition_line="$@"
echo $partition_line \
| csv_column 3 \
| delete_spaces \
| column 1 \
| colons_to_spaces
}
source /usr/bin/shunit2
这里是另一个使用df命令的例子:
DF=df
mock_df_with_eols() {
cat <
Filesystem 1K-blocks Used Available Use% Mounted on
/very/long/device/path
124628916 23063572 100299192 19% /
EOF
}
test_disk_size() {
returns 1000 "disk_size /dev/sda1"
DF=mock_df_with_eols
returns 124628916 "disk_size /very/long/device/path"
}
df_column() {
local disk_device=$1
local column=$2
$DF $disk_device \
| grep -v 'Use%' \
| tr '\n' ' ' \
| awk "{print \$$column}"
}
disk_size() {
local disk_device=$1
df_column $disk_device 2
}
这里我有个例外,为了测试,我在全局域中声明了DF为非只读。这是因为shunit2不允许改变全局域函数。
linux shell整蛊代码,让代码整洁、过程清晰的BASH Shell编程技巧相关推荐
- Linux命令行–基本的bash shell命令
启动shell: /etc/passwd:包含系统用户账户列表以及每个用户的基本配置信息 每个条目有七个字段,每个字段用冒号隔开 用户名 用户密码 用户的系统UID 用户的系统GID 用户的全名 用户 ...
- Linux编程 3 (初识bash shell与man查看手册)
一.初识bash shell 1.1 启动 shell GNU bash shell 能提供对Linux系统的交互式访问.通常是在用户登录终端时启动,登录时系统启动shell依赖于用户账户的配置. ...
- Linux基础之bash shell介绍及基本特性
今天继续讲Linux基础知识,内容是关于bash shell的.分享以下bash shell的相关知识,例如基本特性等. 1.8)bash shell的介绍 1.8.1)什么是bash shell ...
- 认识 BASH Shell
认识 BASH Shell 切换解析度为 800x600 最近更新日期:2005/08/30 文字模式 (command line) 这种指令下达的方式,在 Linux 里面,其实就相当于是 bash ...
- 如何通过终端快速删除文件和目录(bash shell)[关闭]
本文翻译自:How to remove files and directories quickly via terminal (bash shell) [closed] From terminal w ...
- linux上使用git把代码push到gitee上
欢迎大家关注笔者,你的关注是我持续更博的最大动力 原创文章,转载告知,盗版必究 linux上使用git把代码push到gitee上 文章目录: 1 git添加ssh公钥 2 代码推送的流程 从git的 ...
- linux 带ifdef运行程序_如何让linux的一段程序代码进入内核态运行
展开全部 Linux内核的最初部分代码是用汇编语言写的(文件是boot/bootsect.s).(我的汇编水平有限,暂且不看),636f707962616964757a686964616f313333 ...
- Office 远程代码执行漏洞复现过程
本文来自作者肖志华在 GitChat 上分享 「Office 远程代码执行漏洞复现过程」,「阅读原文」查看交流实录. 编辑 | 天津饭 直接贴本地复现过程,至于怎么利用还请自己思考. 2017年11月 ...
- 学习在虚拟机Linux上写c语言代码
记录第一次在虚拟机Linux上写c语言代码的过程 本次实验是在Oracle VM Virtualbox软件中创建的Linux虚拟机上实现的. 目录 1. 安装编译环境 1.1. 先打开Linux的终端 ...
最新文章
- xx.xib: error: Illegal Configuration: Safe Area Layout Guide before iOS 9.0报错问题解决
- 干货丨入门机器学习,从搞懂这8大经典算法开始
- android本地存储SharedPreferences
- 动态网页制作PHP常用的正则表达式
- 12306”的架构到底有多牛逼?
- MATLAB(二)数据的输入
- 360、金山回应网页劫持 没守住商业底线
- 与Android数据库一起工作
- 游戏物体复用:对象池(以Unity3D为例)
- Bootstrap3 表单-输出内联表单
- 如何提取Mac软件的自带图标?
- c语言编写单片机中断,C语言AVR单片机中断程序写法
- java开发一款推箱子游戏
- Unity中location和rotation赋值和更改
- 腾讯职场等级(转载自网络)
- 宝藏世界登录不显示服务器,宝藏世界Trove玩不了怎么办 宝藏世界Trove进不去解决方法汇总...
- 云栖科技评论82期:乌镇上的产业新常态
- Python学习记录(4)元组:戴了紧箍咒的列表
- 《数据安全法》9月1日正式实施,最高可罚1000万元
- 诸葛io的技术架构图_大数据平台的三次浪潮和诸葛io自身架构演变历程 (3)
热门文章
- 闭口式霍尔电流传感器(安科瑞-卓宋兰)
- Django @login_required: 将您重定向的次数过多
- android uevent_open_socket,android 6.0 healthd vold接收uevent
- 《Effective Java》阅读笔记7 避免使用终结方法
- nginx set header
- Eclipse和Idea中workspace,project,moudle等概念
- 2010年12月20日
- leetcode有效的字母异位词--哈希表与Counter(两种方法天差地别)
- 前端学习 -- Css -- 字体的几个属性学习
- mysql----select----练习题(2)