如何在执行前回显实际命令并扩展变量(用它们的值替换)? SO 中也有类似的问题,其中大多数答案建议使用 set -x 或 set -v。不知怎的,这对我来说不起作用。希望您能帮忙找出错误:
myTest.sh的内容
#!/bin/sh
set -v # enable echo command before execution
myTable="TEST_COL890_TABLE"
WhereClause="coL2 > 0"
grep -Eio Col[0-9]+ <<- EOF
SELECT * FROM $myTable
GROUP BY Col1
WHERE $WhereClause
ORDER BY Col3
EOF
set +v # disable echo command before execution
执行者:
$ chmod 744 ./myTest.sh
$ sh ./myTest.sh
控制台输出(注意变量未展开)
myTable=TEST_COL890_TABLE
+ myTable=TEST_COL890_TABLE
WhereClause="coL2 > 0"
+ WhereClause='coL2 > 0'
grep -Eio Col[0-9]+ <<- EOF
SELECT * FROM $myTable
GROUP BY Col1
WHERE $WhereClause
ORDER BY Col3
EOF
+ grep -Eio 'Col[0-9]+'
COL890
Col1
coL2
Col3set +vx # disable echo command before execution
+ set +vx
预期的屏幕输出(变量 $myTable 和 $WhereClause 替换为它们的值)
myTable=TEST_COL890_TABLE
WhereClause="coL2 > 0"grep -Eio Col[0-9]+ <<- EOF
SELECT * FROM TEST_COL890_TABLE
GROUP BY Col1
WHERE coL2 > 0
ORDER BY Col3
EOF
+ grep -Eio 'Col[0-9]+'
COL890
Col1
coL2
Col3
最佳答案
有关 set -v
的 Bash 文档:
Print shell input lines as they are read.
(前面的意思是不做扩展)。
有关 set -x
的 Bash 文档:
Print a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.
我猜 set -x
不会显示重定向的数据,您只能看到 set -v
输出的未展开的读取行。
如果将 EOF
此处文档中使用的文本分配给变量,set -x
将在执行分配时正确显示扩展值。
因此,将您的代码更改为:
select="SELECT * FROM $myTable
GROUP BY Col1
WHERE $WhereClause
ORDER BY Col3"
grep -Eio 'Col[0-9]+' <<< "$select"
关于linux - 在 exec 之前回显命令+变量扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423480/