← Back to Ruby Operators

Backtick

The backtick character is probably best known in Ruby as a way of executing (shelling out to) a command. A lesser-known way this can be done is as part of a heredoc. Let's look at both forms.

# Check if file is tracked by git
def is_git_tracked?(file_path)
  `git ls-files --error-unmatch #{file_path} 2>/dev/null`
  $?.success?
rescue
  false
end

This is a fun example of using backticks from a script of mine. It shells out to git to check if a file is tracked. The $? global variable gets set to the status of the last process and we check for #success?.

The backtick heredoc variation is nothing I've ever seen used in the wild, but rather an oddity I found in the docs.

puts <<-`HEREDOC`
  cat #{__FILE__}
HEREDOC

Run the file that contains this code and it will print out the contents of the file. This can be done with the standard backtick syntax as well.

The reason you may want to use the backtick heredoc variation is that it allows you to bundle a sequence of commands together that run in the same subprocess.

puts <<`SHELL`
  # Set up trap
  trap 'echo "Cleaning up temp files"; rm -f *.tmp' EXIT
  
  # Create temporary file
  echo "test data" > work.tmp
  
  # Do some work
  cat work.tmp
  
  # Trap will clean up on exit
SHELL

See the Ruby Kernel docs for more on this.