我正在制作bash脚本,我需要一个SQL查询,但是它具有bash的转义字符。

我想读取没有bash转义字符的SQL查询,为什么这个转义字符是MySQL的。

QUERY="SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';"


谢谢!

最佳答案

您可以使用

read -r -d '' query <<'EOF'
SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';
EOF

printf "%s\n" "$query"


输出

SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';


编辑,如果您需要扩展变量,请从'中删除​​EOF,例如喜欢:

outfile=/tmp/file
read -r -d '' query <<EOF
SELECT department_id, description FROM departments
INTO OUTFILE '$outfile'
FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';
EOF
printf "%s\n" "$query"


(注意$outfile变量)打印

SELECT department_id, description FROM departments
INTO OUTFILE '/tmp/file'
FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';

10-04 10:36