How to write and execute a shell script to create

2019-08-12 15:49发布

问题:

I created a .sh file in ubuntu to create and execute the following commands and my .sh files and the following mysql scripts are in the same folder. I manually created the test database and I created and ran the scirpts individually.

content of papol.sh

mysql -h localhost -u root -padmin < apple.sql
mysql -h localhost -u root -padmin < getdb.sql

and when i execute the command bash -x papol.sh it throws me the following error

+ mysql -h localhost -u root -padmin
: No such file or directoryapple.sql
+ mysql -h localhost -u root -padmin
: No such file or directorygetdb.sql

I could not find a reason for this. I would be grateful if anyone can help

回答1:

Update

During my next session, I realized mysql wasn't recognized by terminal. I realized i'm dumb and was just always doing things wrong. Do not use alias to resolve to a binary.

Example, do not use alias mysql="/Applications/MAMP/Library/bin/mysql"

Instead

export PATH=$PATH:/Applications/MAMP/Library/bin/

This will allow you to use the binaries appropriately via bash, and you'll also gain access to all mysql binaries including mysqladmin etc from the terminal as well. :) Happy scripting!

Example script with appropriate environment variables:

#!/bin/bash

echo ""
echo Reloading Database 
echo ""
echo Using
echo PROJECT_BUILD_HOME: $PROJECT_BUILD_HOME
echo MYSQL: $(which mysql)
echo PHP: $(which php)
echo ""
echo ""

mysqladmin -u root -pmypass drop projectbuild
mysqladmin -u root -pmypass create projectbuild
gunzip < $PROJECT_BUILD_HOME/pack/projectbuild.sql.gz | mysql -u root -pmypass projectbuild

Old answer below

I had mysql setup in my users .profile as alias mysql="/path/to/mysql".

Instead,

I used export mysql=/path/to/mysql

And in my bash script, I used $mysql.

Example

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