鱼C论坛

 找回密码
 立即注册
查看: 2407|回复: 0

[好文转载] 给大家介绍一个shell代码检查工具

[复制链接]
发表于 2016-8-27 17:19:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x

首先关于shellcheck的安装,有三种方法:
1、直接copy相应shellcheck的可执行文件到bin目录下
2、更换带有shellcheck软件包的源(/etc/apt),然后apt-get update,安装即可
3、进行编译安装,因为shellcheck是用Cabal管理和建立的,所以使用apt-get 安装cabal-install进行编译安装

而关于shellcheck的具体作用:

#### Quoting(引号)

ShellCheck can recognize several types of incorrect quoting:
    echo $1                           # Unquoted variables
    find . -name *.ogg                # Unquoted find/grep patterns
    rm "~/my file.txt"                # Quoted tilde expansion
    v='--verbose="true"'; cmd $v      # Literal quotes in variables
    for f in "*.ogg"                  # Incorrectly quoted 'for' loops
    touch $@                          # Unquoted $@
    echo 'Don't forget to restart!'   # Singlequote closed by apostrophe
    echo 'Don\'t try this at home'    # Attempting to escape ' in ''
    echo 'Path is $PATH'              # Variables in single quotes
    trap "echo Took ${SECONDS}s" 0    # Prematurely expanded trap


#### Conditionals

ShellCheck can recognize many types of incorrect test statements.
    [[ n != 0 ]]                      # Constant test expressions
    [[ -e *.mpg ]]                    # Existence checks of globs
    [[ $foo==0 ]]                     # Always true due to missing spaces
    [[ -n "$foo " ]]                  # Always true due to literals
    [[ $foo =~ "fo+" ]]               # Quoted regex in =~
    [ foo =~ re ]                     # Unsupported [ ] operators
    [ $1 -eq "shellcheck" ]           # Numerical comparison of strings
    [ $n && $m ]                      # && in [ .. ]
    [ grep -q foo file ]              # Command without $(..)

#### Frequently misused commands

ShellCheck can recognize instances where commands are used incorrectly:
    grep '*foo*' file                 # Globs in regex contexts
    find . -exec foo {} && bar {} \;  # Prematurely terminated find -exec
    sudo echo 'Var=42' > /etc/profile # Redirecting sudo
    time --format=%s sleep 10         # Passing time(1) flags to time builtin
    while read h; do ssh "$h" uptime  # Commands eating while loop input
    alias archive='mv $1 /backup'     # Defining aliases with arguments
    tr -cd '[a-zA-Z0-9]'              # [] around ranges in tr
    exec foo; echo "Done!"            # Misused 'exec'
    find -name \*.bak -o -name \*~ -delete  # Implicit precedence in find
    f() { whoami; }; sudo f           # External use of internal functions



#### Common beginner's mistakes

ShellCheck recognizes many common beginner's syntax errors:
    var = 42                          # Spaces around = in assignments
    $foo=42                           # $ in assignments
    for $var in *; do ...             # $ in for loop variables
    var$n="Hello"                     # Wrong indirect assignment
    echo ${var$n}                     # Wrong indirect reference
    var=(1, 2, 3)                     # Comma separated arrays
    echo "Argument 10 is $10"         # Positional parameter misreference
    if $(myfunction); then ..; fi     # Wrapping commands in $()
    else if othercondition; then ..   # Using 'else if'


#### Style

ShellCheck can make suggestions to improve style:
    [[ -z $(find /tmp | grep mpg) ]]  # Use grep -q instead
    a >> log; b >> log; c >> log      # Use a redirection block instead
    echo "The time is `date`"         # Use $() instead
    cd dir; process *; cd ..;         # Use subshells instead
    echo $[1+2]                       # Use standard $((..)) instead of old $[]
    echo $(($RANDOM % 6))             # Don't use $ on variables in $((..))
    echo "$(date)"                    # Useless use of echo
    cat file | grep foo               # Useless use of cat


#### Data and typing errors

ShellCheck can recognize issues related to data and typing:
    args="$@"                         # Assigning arrays to strings
    files=(foo bar); echo "$files"    # Referencing arrays as strings
    printf "%s\n" "Arguments: $@."    # Concatenating strings and arrays.
    [[ $# > 2 ]]                      # Comparing numbers as strings
    var=World; echo "Hello " var      # Unused lowercase variables
    echo "Hello $name"                # Unassigned lowercase variables
    cmd | read bar; echo $bar         # Assignments in subshells



#### Robustness

ShellCheck can make suggestions for improving the robustness of a script:
    rm -rf "$STEAMROOT/"*            # Catastrophic rm
    touch ./-l; ls *                 # Globs that could become options
    find . -exec sh -c 'a && b {}' \; # Find -exec shell injection
    printf "Hello $name"             # Variables in printf format
    for f in $(ls *.txt); do         # Iterating over ls output
    export MYVAR=$(cmd)              # Masked exit codes



#### Portability

ShellCheck will warn when using features not supported by the shebang. For example, if you set the shebang to `#!/bin/sh`, ShellCheck will warn about portability issues similar to `checkbashisms`:
    echo {1..$n}                     # Works in ksh, but not bash/dash/sh
    echo {1..10}                     # Works in ksh and bash, but not dash/sh
    echo -n 42                       # Works in ksh, bash and dash, undefined in sh
    trap 'exit 42' sigint            # Unportable signal spec
    cmd &> file                      # Unportable redirection operator
    read foo < /dev/tcp/host/22      # Unportable intercepted files
    foo-bar() { ..; }                # Undefined/unsupported function name
    [ $UID = 0 ]                     # Variable undefined in dash/sh
    local var=value                  # local is undefined in sh



#### Miscellaneous

ShellCheck recognizes a menagerie of other issues:
    PS1='\e[0;32m\$\e[0m '            # PS1 colors not in \[..\]
    PATH="$PATH:~/bin"                # Literal tilde in $PATH
    echo {1..$n}                     # Works in ksh, but not bash/dash/sh
    echo {1..10}                     # Works in ksh and bash, but not dash/sh
    echo -n 42                       # Works in ksh, bash and dash, undefined in sh
    trap 'exit 42' sigint            # Unportable signal spec
    cmd &> file                      # Unportable redirection operator
    read foo < /dev/tcp/host/22      # Unportable intercepted files
    foo-bar() { ..; }                # Undefined/unsupported function name
    [ $UID = 0 ]                     # Variable undefined in dash/sh
    local var=value                  # local is undefined in sh



#### Miscellaneous
    echo {1..$n}                     # Works in ksh, but not bash/dash/sh
    echo {1..10}                     # Works in ksh and bash, but not dash/sh
    echo -n 42                       # Works in ksh, bash and dash, undefined in sh
    trap 'exit 42' sigint            # Unportable signal spec
    cmd &> file                      # Unportable redirection operator
    read foo < /dev/tcp/host/22      # Unportable intercepted files
    foo-bar() { ..; }                # Undefined/unsupported function name
    [ $UID = 0 ]                     # Variable undefined in dash/sh
    local var=value                  # local is undefined in sh



#### Miscellaneous

ShellCheck recognizes a menagerie of other issues:
    PS1='\e[0;32m\$\e[0m '            # PS1 colors not in \[..\]
    PATH="$PATH:~/bin"                # Literal tilde in $PATH
    rm “file”                         # Unicode quotes
    echo "Hello world"                # Carriage return / DOS line endings
    var=42 echo $var                  # Expansion of inlined environment
    #!/bin/bash -x -e                 # Common shebang errors
    echo $((n/180*100))               # Unnecessary loss of precision
    ls *[:digit:].txt                 # Bad character class globs
    sed 's/foo/bar/' file > file       # Redirecting to input
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-15 15:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表