简体   繁体   中英

Pass as argument a table name in a MySQL command line, in a shell script

I would like to pass as argument a table name in a Mysql command line in a shell script here is my little shell script :

if [ "$1" != "" ]; then
    mysql \
        --user=genome \
        --host=genome-mysql.cse.ucsc.edu \
        -A -D hg38 \
        -e 'desc' "$1" \
        -B -N \
        | awk 'BEGIN {ORS="\t"};{print $1}' | awk '{print "#"$0}'
else
    echo "Error."
fi

So when I try to run my script like this :

bash Script.sh tablename

It returns the following error:

ERROR 1049 (42000): Unknown database 'tablename'

So, few things for your own information:

  • I have access to the database.

  • The table exists in the database when I execute the command with the tablename directly in.

  • I tried alternatively with "desc $1", 'desc "$1"', 'desc "$1" '... always return an error (either ERROR 1049 or 1064).

  • the awk following command lines are not the origin of the problem.

  • I also tried in Python 2.7 with subprocess, and it gave exactly the same error :

    ERROR 1049 (42000): Unknown database 'tablename'

  • I tried to find some help on the web and maybe,it seems that MySQL do not permit to pass table name as argument.

Since I have multiple table to iterate on, I have no other choices.

Thank you in advance for your help.

The argument to -e must be a single string. You're putting the table name as a separate argument from desc , so it's being treated as the database name argument. Change it to:

-e "desc $1"

Here's my whole script:

#!/bin/bash

if [ "$1" != "" ]; then
    mysql \
        -A -D bbodb_test \
        -e "desc $1" \
        -B -N \
        | awk 'BEGIN {ORS="\t"};{print $1}' | awk '{print "#"$0}'
else
    echo "Error."
fi

Then I run:

./scriptname t_users

where t_users is the name of one of my tables.

I omitted the --user and --host arguments because I get them from my ~/.my.cnf file, but I don't think it should make a difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM