echo ${!BASH@} 输出为:BASH BASHOPTS BASHPID BASH_ALIASES BASH_ARGC BASH_ARGV BASH_ARGV0 BASH_CMDS BASH_COMMAND BASH_COMPLETION_VERSINFO BASH_LINENO BASH_REMATCH BASH_SOURCE BASH_SUBSHELL BASH_VERSINFO BASH_VERSION for parameter in ${!BASH*} do echo "The value of ${parameter} is ${!parameter}" done
str="You are a beautiful girl,I do love You" echo ${str/You/She} #输出为She are a beautiful girl,I do love You echo ${str//You/She} #输出为She are a beautiful girl,I do love She echo ${str/You} #输出为are a beautiful girl,I do love You echo ${str//You} #输出为are a beautiful girl,I do love
t="1" echo "no empty t:+${t:+replaceValue}" #输出为no empty t:+replaceValue echo "no empty t${t}" #输出为no empty t1 t="1" echo "no empty t+${t+replaceValue}" #输出为no empty t+replaceValue echo "no empty t${t}" #输出为no empty t1 t="" echo "empty t:+${t:+replaceValue}" #输出为empty t:+ echo "empty t${t}" #输出为empty t t="" echo "empty t+${t+replaceValue}" #输出为empty t+replaceValue echo "empty t${t}" #输出为empty t unset t echo "undefined t:+${t:+replaceValue}" #输出为undefined t:+ echo "undefined t${t}" #输出为undefined t unset t echo "undefined t+${t+replaceValue}" #输出为undefined t+ echo "undefined t${t}" #输出为undefined t
缺失或者为空错误提示
基本形式如下
1 2
${parameter:?Error:parameter is undefined or empty} #当parameter未定义或者为空时,报错 ${parameter:Error:parameter is undefined} #当parameter未定义时,报错
示例如下
1 2 3 4 5 6 7 8 9 10 11 12 13
t="" echo ${t:?Error t is empty or undefined} #报错 ./use-error.sh: line 3: t: Error t is empty or undefined t="" echo ${t?Error t is undefined} #不报错 unset t echo ${t:?Error t is empty or undefined} #报错 ./use-error.sh: line 3: t: Error t is empty or undefined unset t echo ${t?Error t is undefined} ./use-error.sh: line 8: t: Error t is undefined #报错
Bash的内部变量
常用内部变量
变量名
备注
值
$BASH
Bash实例的全路径名
/bin/bash
$HOME
当前用户的home目录
一般是/home/${USER}
$IFS
此变量决定当Bash解析字符串时,如何失败字段或者单词分割线
默认为空格,制表符和换行
$OSTYPE
操作系统的类型
$SECONDS
当前脚本已执行的秒数
$TMOUT
作为Bash内部命令read的默认超时值,指定秒数内未输入,跳过输入,值为空
$UID
当前用户的帐号标识码,与/etc/passwd记录相同
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
echo $BASH echo $HOME set 1 2 3 IFS=',:' #这里再一次体现"$@"与"@*"的区别"$@"="$1$2$3$4...""$*"="${1}${IFS}${2}${IFS}..." echo "$@" echo "$*" echo $* echo $TMOUT TMOUT=3 read a; echo "The value of a is:${a}"
#!/bin/bash set 1a 2b 3c 4d 5f '6d d' oldIfs=$IFS IFS="," echo $* echo "$*" echo $@ echo "$@" echo "arg count:$#" echo 'for arg in $*' i=1; for arg in $* do echo "arg ${i}: ${arg}" let i++ done i=1 echo 'for arg in "$*"' for arg in "$*" do echo "arg ${i}: ${arg}" let i++ done echo 'for arg in $@' i=1 for arg in $@ do echo "arg ${i}: ${arg}" let i++ done echo 'for arg in "$@"' i=1 for arg in "$@" do echo "arg ${i}: ${arg}" let i++ done IFS="$oldIfs"