倒引号(反引号)执行多条命令的问题
1 倒引号是什么
``就是倒引号了,如果是thinkpad一般是ESC下面的那个按键。
在linux中倒引号表示被包起来的部分是命令,且在程序执行时,会被当做命令执行。
2 关于echo `ps`存在的问题
1.1 如果在终端中键入
会发现ps的输出都被放到一行去了,用双引号包起来可以解决
推测是echo的时候把换行符忽略了,但是如果是转换成字符串,换行符又会被解析,所以出现
1.2 如果有如下文本
执行如下命令
得到的结果更奇怪:
只有第一个命令被解析成了命令,后面的都当做了参数
这是因为倒引号时一种扩展,只解析到cat test,之后会被当做纯文本,如果是在shell中执行,只执行一个echo
事实上,cat输出是可以区分出行的,如下:
这样是可以输出2的
所以在倒引号中是不推荐用cat 命令的
3 倒引号的升级版\$()
Note that Backtick is of the Bourne shell. Quoting and escaping becomes quickly a nightmare with it especially when you start nesting them. Ksh introduced the \$(…) alternative which is now standardized (POSIX) and supported by all shells (even the Bourne shell from Unix v9). So you should use \$(…) instead nowadays unless you need to be portable to very old Bourne shells.
一般情况这两者是可以替换的
需要注意的:
3.1 转义字符\在两者中的不同
3.2 嵌套的不同
这里有一些介绍:
Within the backquoted style of command substitution, backslash shall retain its literal meaning, except when followed by: ‘\$’, ‘`’, or ‘\’ (dollar sign, backquote, backslash).
With the $( command) form, all characters following the open parenthesis to the matching closing parenthesis constitute the command. Any valid shell script can be used for command, except a script consisting solely of redirections which produces unspecified results.
The results of command substitution shall not be processed for further tilde expansion, parameter expansion, command substitution, or arithmetic expansion. If a command substitution occurs inside double-quotes, field splitting and pathname expansion shall not be performed on the results of the substitution.
4 倒引号和单引号、双引号的区别
‘string’ 单引号 (single quote)
被单引号用括住的内容,将被视为单一字串。在引号内的代表变数的$符号,没有作用,也就是说,他被视为一般符号处理,防止任何变量替换。12heyyou=homeecho '$heyyou' # We get $heyyou“string” 双引号 (double quote)
被双引号用括住的内容,将被视为单一字串。它防止通配符扩展,但允许变量扩展。这点与单引数的处理方式不同。12heyyou=homeecho"$heyyou" # We get home`command` 倒引号 (backticks)
在前面的单双引号,括住的是字串,但如果该字串是一列命令列,会怎样?答案是不会执行。要处理这种情况,我们得用倒单引号来做。12fdv=\`date +%F\`echo "Today $fdv"
在倒引号内的 date +%F 会被视为指令,执行的结果会带入 fdv 变数中。