簡體   English   中英

圍繞擴展變量的 Bash HEREDOC 單引號

[英]Bash HEREDOC Single Quotes around expanded variable

我需要 $table var 來擴展,但同時保留 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';

您可能想要分解其他命令正在執行的操作以確保錯誤在哪里。

附帶說明一下,您提到通過引號(' 或“)關閉變量擴展顯然將此處文檔的語法與管道中其他命令的不相關語法混為一談。

例如這是正確的:

### 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' ,關閉了變量擴展。 這與管道中的其他命令(即grep 'hello hello' )是否有引號無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM