第180页 | Learning the Bash Shell | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

Potential Problems

Here are some useful things to watch out for when writing shell scripts. Being aware of them will not only save you time in tracking down bugs but will also make your scripts more robust, more readable, and above all, more maintainable.

 

 
Don't create massive scripts or functions that try to do everything. Split functionality up into smaller units and place them in functions. This not only makes the code easier to read but makes it easier to debug.Always place the shell execution directive (e.g., #!/bin/bash) at the top of your scripts to ensure they will be run by bash.Don't use reserved words for variable names. This can become very confusing:

let let="echo"
let echo="hello"
echo "$echo world"

 

 
Be careful with whitespace. Attempting the following assignment will not give the expected result:

cat = 5

 

 
Don't use the same names for variables and functions:

function letter
{
     echo $1etter
}

letter=letter
letter letter

This causes more confusion that it's worth. While this example is contrived, be on your guard for more subtle examples. To guard against this, try and name your functions using verbs, e.g., function print_letter. Be careful when using the test operator [...]. The following two if statements are not the same, although they look very similar:

         if [ "$var" = 42 ]
         if [ "$var" -eq 42 ]

The first is a string comparison, the second an integer comparison. We suggest using ((...)) for arithmetic comparisons in if statements.

 

 

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


上一页 · 目录下一页


下载 · 书页 · 阅读 ‧ 电子书库