Bash HEREDOC扩展变量的单引号



我需要$table变量展开,但同时保留MSSQL为table_name参数所需的引号。我不知道这是否可能,因为我一直在寻找一段时间。我看到的常见答案是,如果有任何引号,那么变量将不会展开。难道我在这里做不到我想做的吗?

cat <<EOF | isql $host sa 'password' -d, | sed '-e 1,10d;$d' | sort > mssql_table_${table}_column_info
use $database;
select column_name from information_schema.columns where table_name = '$table';
EOF

期望输出值

select column_name from information_schema.columns where table_name = 'mytable_name';

注意,输出的表名周围仍然有单引号。这对于MSSQL选择合适的表是必要的。

您确定这里文档中的变量扩展是问题所在吗?如果您只是检查cat命令的输出(使用bash):

$ database=database123 table=mytable_name cat <<EOF >/dev/stdout
use $database;
select column_name from information_schema.columns where table_name = '$table';
EOF
use database123;
select column_name from information_schema.columns where table_name = 'mytable_name';

您可能需要分解其他命令的操作,以确定错误在哪里。

顺便说一句,您提到通过引号('或")关闭变量展开,显然将here文档的语法与管道中其他命令的不相关语法混淆了。

例如:

### works, prints 'hello hello'
MYVAR='hello' cat <<EOF | grep 'hello hello'
hello $MYVAR
EOF

相对于:

### WRONG, response empty
MYVAR='hello' cat <<'EOF' | grep 'hello hello'
hello $MYVAR
EOF

是否执行变量替换,因为'EOF'在here文档中被引用,关闭变量扩展。不管管道中的其他命令(即grep 'hello hello')是否有引号,

最新更新