Find the answer to your Linux question:
Results 1 to 3 of 3
I have a MySQL back up script that I am working on in bash. I am fairly new to bash scripting and am having a minor problem with it. What ...
  1. #1
    Just Joined!
    Join Date
    Jan 2010
    Posts
    1

    Bash Script Problem...

    I have a MySQL back up script that I am working on in bash. I am fairly new to bash scripting and am having a minor problem with it. What I am trying to accomplish is a execute a "SHOW SLAVE HOSTS" in MySQL and pull out the ServerID for the server that is being backed up and then do the same query, but this time look for MySQL servers that are SLAVES of the server that is about to be backed up so I can stop the slave thread on those hosts so temp tables do not end up getting corrupted (It is a long explanation as to why this is necessary).

    The problem is with the second command. The command itself is fine, the problem is with BASH replacing the $masterID variable with its value. Anyone have any pointers as to what I might be doing wrong here?

    Code:
    masterID=`mysql --batch --skip-column-names -e "show slave hosts"|grep $ip|awk '{print $1}'`
    
    slaveIP=`mysql --batch --skip-column-names -e "show slave hosts"|awk '{if ($5 == $masterID) print $0}'|awk {'print $2'}`
    Thanks,

    Whit3fir3

  2. #2
    Linux Newbie
    Join Date
    Jul 2008
    Posts
    181
    Single quotes prevent variable substitution. Compare

    echo "$HOME"

    vs.

    echo '$HOME'

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    It does indeed appear to be a quote issue, exactly as burschik said. However, because you are mixing both Bash variables and awk variables, you will need to play around with quoting a bit.

    For instance, in this line:
    Code:
    awk '{if($1 == "'$myvar'") print}' file
    We need single quotes because of the { } (which will be stolen by Bash otherwise), but the single quotes will prevent $myvar from being replaced by Bash. So we need the $myvar to be outside of quotes (or in double quotes), but need its value to be surrounded by quotes inside of the awk statement...

    See? It can get very complicated to play with this stuff. An easier solution might be:
    Code:
    awk "{if(\$1 == '$myvar') print}" file
    In this case, the entire thing is double-quoted, which means that Bash will replace variables. However, $1 (the awk variable) is escaped as \$1, which means that Bash does not see it as a variable, and simply passes the "$" and "1" characters into awk. And then awk sees it as a variable, and uses it correctly.

    Does this all make sense?
    DISTRO=Arch
    Registered Linux User #388732

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...