首页 > shell脚本有两个地方代码读不懂?

shell脚本有两个地方代码读不懂?

这个是 suse 11 的 /sbin/service脚本

问题.这两部分的代码是什么意思呢?

  1. if test "${1::1}" = "-"; then

  2. args="${args:+$args }$1"

  3. 脚本里面反复出现的 1>&2 究竟是要输入到哪个文件呢?
    具体上下问在下面贴上

问题.网上有没有专门介绍 /sbin/service 这个脚本功能的文章可以参考一下呢?

linux-d5wb:/sbin # cat service 
#!/bin/sh
#
# /sbin/service        Handle boot and runlevel services
#

#
# Only root should do
#
if test "$(id -u)" -ne 0; then
   echo "${0##*/}: only root can use ${0##*/}" 1>&2
   exit 1
fi

#
# Location of our service scripts
#
RCDIR="/etc/init.d"

#
# Clean environment
#
PATH=/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin
test -n "$TERM" || TERM=raw
LANG=POSIX
export PATH TERM LANG

exec_rc ()
{
    env -i LANG=$LANG PATH=$PATH TERM=$TERM ${1+"$@"}
}

usage ()
{
    echo "Usage: ${0##*/} [--help | --status-all | <service> [<args>| --full-restart]]" 1>&2
    exit 1
}

help ()
{
    echo "Usage: ${0##*/} [<options> | <service> [<args> | --full-restart]]"
    echo "Available <options>:"
    echo "  -h,--help        This help."
    echo "  -s,--status-all  List out status of all services."
    echo "Usage for specific <service>:"
    echo "  ${0##*/} service_name argument [option]"
    echo "  ${0##*/} service_name --full-restart"
    echo "  ${0##*/} --full-restart service_name"
    exit 0
}

  status_all=0
full_restart=0
        args=""
while test $# -gt 0; do
    opt=
    if test "${1::1}" = "-"; then
    if test ${#1} -gt 2 -a "${1::2}" = "--" ; then
        opt="${1:2}"
    else
        opt="${1:1}"
    fi
    shift
    else
    args="${args:+$args }$1"
    shift
    continue
    fi

    case "$opt" in
    status-all|s)   status_all=1 ;;
    full-restart) full_restart=1 ;;
    h*)                help ;;
    *)               usage ;;
    esac
done

问题:

1 if test "${1::1}" = "-"; then
${string:position:length}在$string中, 从位置$position开始提取长度为$length的子串

2 args="${args:+$args }$1"
${var:+OTHER}如果var被设置了, 那么其值就是$OTHER, 否则就为null字符串

这两个问题都是shell的字符串操作和处理。

3 脚本里面反复出现的 1>&2 究竟是要输入到哪个文件呢?
1表示标准输出,2表示标准错误输出,1>&2表示把标准输出的内容重定向到标准错误输出,这样无论程序是使用了哪种,或两种都使用,我们都可以抓到它的所有输出。

【热门文章】
【热门文章】