rubyrakesingle-quotesbackquote

Process single quoutes inside back quoute statement in rake/ruby


I need to execute the following shell command and read out the output in rake variable:

`#{security_bin} find-identity -v -p codesigning #{keychain_path} | grep "$1" | awk -F\" '/"/ {print $2}' | head -n1`

As you can see, I am using back quotes to tell rake interpreter that "this is a shell command to execute". The problem is that it won't work since usage of single quotes inside the call breaks the parsing or something, and ruby doesn't know where the entry ends.

The error I am getting is the following:

rake xamarin:create_keychain
Deleted the old one...
About to retrieve identity...
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file

The function within which the flow happens is the following (though I still suspect the line mentioned above:

def create_temp_keychain(keychain_path, p12path)
    security_bin='/usr/bin/security'

    delete_keychain(keychain_path)

    `/usr/bin/security create-keychain -p tempass #{keychain_path}`
    `#{security_bin} set-keychain-settings -lut 7200 #{keychain_path}`
    `#{security_bin} unlock-keychain -p "tempass" #{keychain_path}`
    `#{security_bin} import #{p12path} -P "" -A -t cert -f pkcs12 -k #{keychain_path}`
    `#{security_bin} list-keychain -d user -s #{keychain_path} "login.keychain"`
    puts "About to retrieve identity..."
    identity_output = `#{security_bin} find-identity -v -p codesigning #{keychain_path} | grep "$1" | awk -F\" '/"/ {print $2}' | head -n1`
    puts identity_output
end

What is the correct way to execute the following command in ruby?


Solution

  • Double quotes should be escaped twice as in:

    awk -F\\" '...
    

    in order to process shell double quote in backtick-based shell call in ruby.

    The correct line would be:

    `#{security_bin} find-identity -v -p codesigning #{keychain_path} | grep "$1" | awk -F\\" '/"/ {print $2}' | head -n1`
    

    Credit for the answer goes to @mudasobwa.