如何在bash脚本中忽略转义字符?

时间:2017-04-01 15:20:06

标签: mysql sql bash csv

我正在创建一个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';"

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用

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';