Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape the "return" function in a bash script

Tags:

bash

shell

mysql

The script below is loading in a bunch of csv files into a mysql db. I am trying to execute this function within the loop but the mysql table field called return is causing the script to think it should execute the function return.

The ` around return is to escape it for mysql, its a mysql keyword.

for f in *.txt; 
do 
 mysql -uroot -ppassword -e "LOAD DATA INFILE '$f' INTO TABLE info FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (`return`,`id`,`field1`,`field2`);"; 
done
like image 248
zer0bit Avatar asked Dec 21 '12 19:12

zer0bit


People also ask

What does \r do in Bash?

The -r tests if the file exists and if you have read permission on the file. Bash scripting tutorial - if statement. The meaning of -r depends on what program/command it is given as an argument for. In this case it is for [ , and means to check whether the file named by the next argument is readable.

Does return exit a script?

The return keyword exits a function, script, or script block.

How do you exit a function in Bash?

We use exit to exit from a Bash script. In that case, the script exits with the exit status set to the integer argument. If we don't pass an argument to exit, it exits with the exit status set to the exit status of the last command executed before exit.

What does exit return in Linux?

exit exits the calling shell or shell script with the exit status specified by n . If you omit n , the exit status is that of the last command executed (an end-of-file exits the shell). return exits a function with the return value specified by n . If you omit n , the return status is that of the last command executed.


2 Answers

it's the stupid quoting convention in mysql of using backtick characters. Can you use Single-quotes instead, ie ', ie 'return'?

Backticks mean "perform command substitution in this current command in the shell", so it is trying to run the command return.

If you can't use 'return' then you can escape ALL of the backticks, like

\`return\`

IHTH

like image 76
shellter Avatar answered Oct 09 '22 07:10

shellter


This happen because strings enclosed by ` ` are executed by bash.

Try this:

echo '` date `' # this output the string ` date `
echo "` date `" # this output current time

But you cannot change double quotes with single one, because you need $f to be sostituded with variable. So escape backtick with \.

like image 42
Alessandro Pezzato Avatar answered Oct 09 '22 08:10

Alessandro Pezzato