Frostfyre
Frostfyre

Reputation: 201

Execution of dynamic mysql query fails

In a recent bash script, I required a function to standardize calls to a mysql server. My first version of the function looked like this:

mysqlfunc()
{
    args="-A"
    if [ "$1" = "++" ]; then
        shift
        while [ 1 ]; do
            if [ "$1" = "--" ]; then
                shift
                break
            fi
            args="$args $1"
            shift  
        done
    fi

    query="-e \"$*\""
    if [ -f "$1" ]; then
        query="< $1"
    fi

    mysql $args -h<host> -p<password> -P<port> -u<user> <database> $query
}

This version of the function produced a syntactically correct mysql statement; executing the evaluated command on the command line worked without error. However, when a file was passed to the function, such as:

mysqlfunc $DB_Scripts/mysql_table_create.sql

The mysql command would fail, complaining of what appeared to be either incorrect arguments supplied or incorrect syntax. It didn't specify which, only printed the usage help for mysql.

My question: Why does this dynamic statement assignment fail?


Example:

Function call:

mysqlcmd $PATH_TO_FILE/example.sql

Mysql command executed:

mysql -A -h<host> -p<password> -P<port> -u<user> <database> < <path_to_file>/example.sql

Result:

Usage for mysql printed to the terminal

Upvotes: 0

Views: 208

Answers (2)

Calvin Taylor
Calvin Taylor

Reputation: 694

can you do something like

if [ -f "$1" ]; then
  cat $1 | mysql $args -h<host> -p<password> -P<port> -u<user> <database>
else
  mysql $args -h<host> -p<password> -P<port> -u<user> <database> $query
fi

works with psql

Upvotes: 0

Etan Reisner
Etan Reisner

Reputation: 80931

You can't put shell metacharacters like < inside variables and have them function.

That's not how the parser works. The shell doesn't see the < in the variable result as a redirection operator it sees it as a literal string.

This is part of what Bash FAQ 050 covers.

Upvotes: 1

Related Questions