我做了同样的事情,除了我的情况是 mysql 。我正在使用zsh。我设置了一个别名,这样当我调用脚本时,shell 就不会做任何 globbing,这样我就可以做到这一点:
$ sql select * from Table
代替:
$ sql select '*' from Table
别名是:
alias sql='noglob sql'
我还sed
习惯在必要时自动添加引用,以便我可以这样做:
$ sql select * from Client where first_name like John% and last_name = Wiley
代替:
$ sql select '*' from Client where first_name like "'John%'" and last_name = "'Wiley'"
在我不希望 shell 脚本自动添加引号的情况下,我会省略 = 运算符前后的空格,如下所示:
$ sql select t1.col1,t2.col2 from Table1 t1 join Table t2 on t1.client_id=t2.client_id.
我将脚本粘贴在这里,以防您从中获利。它是 zsh 和 mysql 特定的。您必须修改它以适应您传递要在 psql 中运行的 sql 命令的方式。脚本中使用的mpager
程序是另一个 shell 脚本,它调用 vim 并要求它充当适合浏览表格输出的寻呼机:
#!/usr/bin/zsh
function usage() {
echo -n "Usage: $0 [-h] [-t] [-d db] [-q] [-v] [-n] [p] [-q] [sql commands]
-d db Use specified database instead of the default one
-t Do not 'tabularize' (borders) the output
-v Be verbose
-n Dry-run - show what command to be executed
-p Pipe output to mpager
-q Surpress own output, only show output from mysql
-h Show this help message
"
}
password=${DB_PASS:-secret}
db=${DB:-default_db}
user=${DB_USER:-username}
USE_TABLE='--table'
while getopts d:tvnhpq o
do
case "$o" in
d) db=$OPTARG ;;
t) USE_TABLE='' ;;
v) verbose=1 ;;
n) dry_run='echo' ;;
p) use_mpager=t ;;
h) usage; exit 0 ;;
q) quiet=1;;
*) usage;
exit 1 ;;
esac
done
shift `expr $OPTIND - 1`
case $2 in
database|databases)
db=
;;
esac
if [ -z "$quiet" -a -n "$db" ]; then
echo 1>&2 "Database: $db"
fi
if [ $# -lt 1 ]; then
mysql --table -u $user -p$password $db "$@"
exit
fi
to_run=`echo $*|sed -e "s/ \(=\|like\) *\([^'][^ ]*\+\)/ \1 '\2'/g"`
# This helps for debugging. Show what is going to run when output is going to a
# terminal:
if [ -t 1 ]; then
echo "to_run: $to_run" 1>&2
fi
if [ -n "$verbose" ]; then
echo "mysql $USE_TABLE -u $user -p$password $db -e ${(q)to_run}"
fi
if [ -n "$use_mpager" ]; then
$dry_run mysql $USE_TABLE -u $user -p$password $db -e "$to_run" | mpager
else
$dry_run mysql $USE_TABLE -u $user -p$password $db -e "$to_run"
fi