linux - 在 exec 之前回显命令+变量扩展

标签 linux bash

如何在执行前回显实际命令并扩展变量(用它们的值替换)? 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
Col3

set +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/

相关文章:

linux - 使用 awk 多次打印该列

python - 在 GCE 上部署后的 Django FileNotFound 错误

bash - 向 WSL 自动完成建议添加常用命令

bash - 如何使用 Bash 为变量引用文件?

linux - 将命令保存到变量中而不是运行它

python - hcitool lescan不会实时打印到一个文件

linux - 更新 Scala 版本

bash - bash 的代码格式化程序/美化程序(在命令行中)?

bash - 我在 "gem uninstall rails"时遇到错误

linux - 根据用户输入创建文件