2

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.

  • 1
    Quoting variables may help. You should quote them anyway. – Kamil Maciorowski Jan 3 at 13:04
  • You should quote the word following the redirection operator <, like this "$currdir/$exname.sql". If it expands to more than one word, bash reports an error. – Stefan Hamcke Jan 3 at 13:08
  • Quoting the variable expansions is the correct thing to do. However, not quoting them would in this case (with the values of the variables shown here) not be an issue. Since the error message is indicating line 31 in a script, and you only show less than 15 lines, I'd be interested in seeing line 31... – Kusalananda Jan 3 at 13:10
  • 2
    Maybe his $PWD has a space character @Kusalananda – Stefan Hamcke Jan 3 at 13:11
  • @StefanHamcke Ah. Yes. – Kusalananda Jan 3 at 13:12
3

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:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.