环境变量未在命令行参数内展开

Ani*_*nil 2 shell bash awk quoting variable-substitution

我有一个文件user-pid.out2,其中包含“usernumber”和“process id”作为两列。根据用户编号我想找到相应的进程ID。下面的前两行没有正确显示输出,但是当我在第 3 行和第 4 行中将用户硬编码为 62 时,它显示了与用户 62 对应的进程 ID。有人可以帮忙吗?

USR=62
usrpid=`awk '$1 == "$USR" {print $2}' /home/hu/batchhu/dbscripts_tst2/user-pid.out2`
echo "first:" $USR $usrpid
# This shows 62 and blank for process id

usrpid=`awk '$1 == "62" {print $2}' /home/hu/batchhu/dbscripts_tst2/user-pid.out2`
echo  "second:" $USR $usrpid
# This shows 62 and process id corresponding to this user in the file user-pid.out2
Run Code Online (Sandbox Code Playgroud)

gle*_*man 9

@artm 展示了一种技术,您可以在其中双引号 awk 脚本并转义各种字符。这是其他 3 种技术

跳出单引号让shell扩展变量

usrpid=$(awk '$1 == "'"$USR"'" {print $2}' file)
Run Code Online (Sandbox Code Playgroud)

将 shell 变量传递给 awk 变量

usrpid=$(awk -v usr="$USR" '$1 == usr {print $2}' file)
Run Code Online (Sandbox Code Playgroud)

如果变量是导出的,使用awk的ENVIRON数组

usrpid=$(awk '$1 == ENVIRON["USR"] {print $2}' file)
Run Code Online (Sandbox Code Playgroud)

后者应该是首选。

在第一种方法中,例如@artm 的方法,shell 变量的内容嵌入在awk代码中,因此如果变量的内容没有受到严格控制(例如,使用,会调用),这将成为命令注入漏洞USR='blah" || system("reboot") || "'reboot

第二个不会引入命令注入漏洞,但如果$USR包含反斜杠字符,则该usr awk变量将不会包含与$USRshell 变量相同的内容,因为awk在那里展开类似 C 的反斜杠转义序列。

使用ENVIRON没有这些问题。