我正在尝试使用 shell 变量打印 sql 语句,但没有得到预期的输出:
pdate=`date +%d-%b-%Y`
query='"select \* from table_name where partition_date='"$pdate"' and \$CONDITIONS"'
echo $query
预期输出:
"select * from table_name where partition_date="30-Nov-2018" and \$CONDITIONS"
实际输出:
"select \* from table_name where partition_date=30-Nov-2018 and \$CONDITIONS"
答案1
要获得您想要的输出:
pdate=$(date +%d-%b-%Y)
query='"select * from table_name where partition_date="'"$pdate"'" and \$CONDITIONS"'
# ............^^ no backslash ........................^..........^ quotes as plain chars
echo "$query"
bash 的另一种方法是printf
:允许您简化引用
printf -v query '"select * from table_name where partition_date="%s" and \$CONDITIONS"' "$pdate"