Shell中\$i \$() \${}的区别

shell中奇葩写法不仅仅是(.)、{.}、((.))等等写法,还有各种奇怪的写法和细节需要注意,一个不留神就发现结果和预期不一样

首先我们演示一个基本的

1
2
a = "b"
echo $a

结果是什么都没打印,正确写法是=两边没有空格a="b"

认识到shell中的奇葩写法后,需要对各种写法有个基本的认识

  1. 不加括号,正常的取值方式,但是在引号中不好使。
  2. 单引号。原样输出,但仍然会解析\${var}
  3. 双引号。会解析\${var} 、\$var和命令\$(expr)
  4. \${}。取值操作
  5. 反引号`。当作命令执行
  6. \$()。括号中的内容当做命令执行

然后我们再来看下这些写法的使用情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
i=i

# 正常的取值,1
echo $i

# 原样输出,$i
echo '$i'

# 正常取值,1
echo "$i"

# 正常取值,1
echo ${i}

# 当做命令执行
echo `date -d "1 days ago" +"%Y-%m-%d"`

# 当做命令执行
echo $(date -d "1 days ago" +"%Y-%m-%d")

再来一个同时有单引号和双引号的,这里就不能用\$ds了,只能用\${ds}

1
echo "insert overwrite table table_name partition (ds='${ds}') select distinct name from table_name_pre where ds='${ds}';"

$变量说明:
$$ Shell本身的PID(ProcessID)
$! Shell最后运行的后台Process的PID
$? 最后运行的命令的结束代码(返回值)
$- 使用Set命令设定的Flag一览
$* 所有参数列表。如”$*”用「”」括起来的情况、以”$1 $2 … $n”的形式输出所有参数。
$@ 所有参数列表。如”$@”用「”」括起来的情况、以”$1” “$2” … “$n” 的形式输出所有参数。
$# 添加到Shell的参数个数
$0 Shell本身的文件名
$1 ~ $n 添加到Shell的各参数值。$1是第1参数、$2是第2参数…。

示例:

1
2
3
4
5
6
7
8
9
printf "The complete list is %s\n" "$$"
printf "The complete list is %s\n" "$!"
printf "The complete list is %s\n" "$?"
printf "The complete list is %s\n" "$*"
printf "The complete list is %s\n" "$@"
printf "The complete list is %s\n" "$#"
printf "The complete list is %s\n" "$0"
printf "The complete list is %s\n" "$1"
printf "The complete list is %s\n" "$2

执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
> sh params.sh 123456 QQ

The complete list is 24249
The complete list is
The complete list is 0
The complete list is 123456 QQ
The complete list is 123456
The complete list is QQ
The complete list is 2
The complete list is params.sh
The complete list is 123456
The complete list is QQ