0

I'm new to writing shell scripts.

I am attempting to create a database using a shell script. Here's the script:

#!/bin/bash
#create a new db
a="mysql -uuser -ppassword -e'create database $1;'"
exec $a

The command exec mysql -uuser -ppassword -e'create database databaseName;' works in a shell, but when I sh the script, I get the mysql help open...

1

3 Answers 3

1

I think the problem is in the quotes, the simple quote prevent the variable expansion. You can simply do like this in your script:

    #!/bin/bash
    #create a new db

    mysql -u user -p password -e "create database $1;"

Or you can try to place all your mysql commands in a file, let's say "dbname.sql". And do this:

    #!/bin/bash
    #create a new db

    mysql -u user -p password "$1" < "$1.sql"
Sign up to request clarification or add additional context in comments.

Comments

1

if you like use exec to run commands this can be a possible solution

    #!/bin/bash
    #create a new db
    programm="mysql"
    parameter[0]="-ppassword"
    parameter[1]="-uuser"
    parameter[2]="-ecreate database $1;"
    exec "$programm" "${parameter[@]}"

exec parameter are

exec [-a NAME] [-cl] [COMMAND] [ARG...] [REDIRECTION...]

command is $programm and the array parameter is the argument list.

Comments

0

Sounds like you need to use the 'cat' command and a pipe instead of using 'exec' .

cat /path/to/my/file | mysql -h localhost -u root -padmin

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.