1

i want to import a database with mysql (running with MAMP):

#! /bin/bash
# variables
currdir=$PWD
dbname=TEST
dbuser=root
dbpass=root
dbpath="/applications/MAMP/Library/bin"
exname=database

if [ "$1" = "import" ]
then
  cd $dbpath
  ./mysql -u $dbuser -p$dbpass $dbname < $currdir/$exname.sql
fi

if my script and files are on a different volume as the mysql bin i get an

line 31: $currdir/$exname.sql: ambiguous redirect

error, if they are on the same volume the import works. is it a permission error? echoing all variables give values, they are not empty, also first reading the file into a variable with

value=$(<$exname.sql)

does not work, though $value holds the contents of the file? is it the cd? i tried to run mysql directly without the cd:

# cd $dbpath
/applications/MAMP/Library/bin/mysql -u (...)

but it also does not work.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
fffwww
  • 11

1 Answers1

2

Variable expansions should be quoted to prevent

  1. splitting of their values into separate words
  2. filename globbing on the resulting words (less of an issue in your case, possibly).

If $PWD contains a space, and if the IFS variable has the default value (a space, tab and newline), then $currdir/$exname.sql would be split into at least two words. This would then give rise to your "ambiguous redirect" error message in bash.

To resolve this, quote all variable expansions (especially $dbpass as passwords usually contains special characters):

if [ "$1" = "import" ]; then
  ( cd "$dbpath" &&
    ./mysql -u "$dbuser" -p"$dbpass" "$dbname" <"$currdir/$exname.sql" )
fi

Here, I have additionally done the cd and the mysql call in a subshell as to prevent the cd from changing the working directory for the rest of the script (although it's not clear why you actually need the cd in the first place).

Related:

Kusalananda
  • 333,661