字符串

字符串

字符串是 shell 编程中最常用最有用的数据类型,单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;双引号中则允许引入变量:

# 使用双引号拼接
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"

# 使用单引号拼接
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !' # hello, ${your_name} !

字符串常见的操作如下:

string="string"

# 获取字符串长度
echo ${#string}

# 提取子字符串
${string:1:4}

# 查找子字符串
echo `expr index "$string" io`

引号

您的 Bash Shell 可以理解具有特殊含义的特殊字符。例如,$var 用于扩展变量值。Bash 扩展变量和通配符,例如:

echo "$PATH"
echo "$PS1"
echo /etc/*.conf

但是,有时您不希望使用变量或通配符。例如,不要打印 $PATH 的值,而只是在屏幕上将 $PATH 作为单词打印。您可以通过将特殊字符的含义用单引号引起来来启用或禁用。这对于在编写 Shell 脚本时抑制警告和错误消息也很有用。

echo "Path is $PATH"  ## $PATH will be expanded
echo 'I want to print $PATH' ## PATH will not be expanded

引号分为三种:

Quote type Name Meaning Example (type at shell prompt)
" The double quote The double quote ( “quote” ) protects everything enclosed between two double quote marks except $, ‘, " and .Use the double quotes when you want only variables and command substitution. _ Variable - Yes _ Wildcards - No * Command substitution - yes The double quotes allowes to print the value of $SHELL variable, disables the meaning of wildcards, and finally allows command substitution. echo "$SHELL"echo "/etc/*.conf"echo "Today is $(date)"
' The single quote The single quote ( ‘quote’ ) protects everything enclosed between two single quote marks. It is used to turn off the special meaning of all characters. _ Variable - No _ Wildcards - No * Command substitution - No The single quotes prevents displaying variable $SHELL value, disabled the meaning of wildcards /etc/*.conf, and finally command substitution ($date) itself. echo '$SHELL'echo '/etc/*.conf'echo 'Today is $(date)'
\ The Backslash Use backslash to change the special meaning of the characters or to escape special characters within the text such as quotation marks. You can use \ before dollar sign to tell the shell to have no special meaning. Disable the meaning of the next character in $PATH (i.e. do not display value of $PATH variable): echo "Path is \$PATH"echo "Path is $PATH"

\ 可以用来进行换行衔接:

echo "A monkey-tailed boy named Goku is found by an old martial \
>arts expert who raises him as his grandson. One day Goku meets a \
>girl named Bulma and together they go on a quest to retrieve the seven Dragon Balls"

# Purpose: clean /tmp/$domain ?
check_temp_clean() {
        [ "$SERVER_MODE" = "daemon" ] || return 1
        [ "$SERVER_MODE"  = "init"    ] && return 0
        # note use of the backslash character to continue command on next line
        [ "$SERVER_MODE"  = "clean" \
          -a -e /usr/local/etc/nixcraft/lighttpd/disk_cache.init ] && return 0
        return 1
}
上一页