Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Cheatsheet for git, rails, unix etc.

Jsonb AR querying:


  • Version of git

    git --version

  • View user name and email for current user:

    git config

    git config

  • Change user name and email for current repository:

    git config "Gagan"

    git config ""

  • Change user name and email for all repositories:

    git config --global "Gagan"

    git config --global ""

  • Set the colors for git:

    git config --global color.ui true

  • Set default pager for git

    #Default is less. Setting to '' will stop the use of pager
    git config --global core.pager ''
  • Add a git remote:

    git remote add <remote-name> gt@giturl.git

  • Remove a git remote:

    git remote rm <remote-name>

  • View git remotes: git remote -v

Pulling, adding, committing and related commands
  • To add the same file in patches, so that they can be committed under different commits:

    git add filename -p

  • To stage all the files that are delete locally:

    git rm $(git ls-files --deleted)

  • To see the difference of files that are staged

    git diff --cached or git diff --staged

  • To see more context than just 3 lines in a git diff

    git diff -U7

  • To change your last commit message do

    git commit --amend

  • To push from a branch to github do

    git push origin <local-branchname>(:<remote-branchname>)

  • Dry run your push

    git push --dry-run origin <local-branchname>(:<remote-branchname>)

    It is often better to test out what changes will happen with you push. The options to use to do that is --dry-run

Listing files
  • deleted files:

    git ls-files --deleted

  • all untracked files:

    git ls-files -o

  • all files that git has ignored:

    git ls-files --exclude-standard

  • untracked files that git doesn't ignore (i.e. all new files):

    git ls-files --other --exclude-standard

  • Files that match a pattern:

    git ls-files vendor*

  • Removing ignored file from the repository:

    To delete a file from the repository but keep it in your working directory (this might come in handy when the file has been ignored)

    git rm --cached <file>


Remove untracked files dry run: git clean -n

clean untacked files

git clean -f

OR rm -r $(git ls-files --other --exclude-standard)

clean untracked files and directories

git clean -f -d

git clean untraced files including ignored files

git clean -f -x

options -d removes directory -n dry-run, -f force, -x remove files ignored by .gitignore

  • To revert changes done to a particular file in a particular commit you can use the command.

    git checkout <sha-of-commit> <path-to-file>

  • When in the middle of conflict while merging branches

    And you want to keep the changes in a file as the were in the trunk:

    git checkout --ours index.html

    or you want to keep changes in a file as they were in the branch:

    git checkout --theirs layouts/default.html

  • Adding a tag git tag -a '<tag-number>' -m 'tag-message'

  • push all tags git push --tags

  • delete tag locally git tag -d <tag-number>

  • delete a tag in the repository that has been remove locally git push origin :refs/tags/<tag-number>

  • add a tag to the sha git tag <tag-number> <sha-of-commit> -m "message of tag"

branching & merging
  • To see all branches including all branches (ie local and remote):

    git branch -a

  • To create a new branch from a particular commit that exists in the log of current branch

    git branch branchname sha-of-commit

  • Delete a branch in repository that is deleted locally

    git push origin :feature/sass i.e. add colon before the branch name

  • Create a branch from a previous commit: git branch branchname <sha1-of-commit>

  • List existing remote branches: git ls-remote --heads

  • Use a mergetool to help resolve conflicts git mergetool

  • Git's Graphical user interface git gui
  • Find the commit that introduces a bug using git bisect. See git bisect start

    git bisect good <sha-of-good-commit>

    git bisect bad <sha-of-bad-commit>

    git bisect run rspec spec/features/my_broken_spec.rb #To automate the bisect feature.

  • To view recent commit on the current branch with each commit on one line git log --pretty=oneline

    git ref log

  • View changes in one branch that do not exist in the other git log branch1 --not branch2

  • You can use the -- option in git log to see the commit history for a file, even if you have deleted the file git log -- [file_path]



  • To push develop to heroku

    git push heroku develop:master

  • Add a remote to heroku repo url

    heroku git:remote -a appname

  • Get a local dump for a pg database on heroku:

    curl -o latest.dump $(heroku pgbackups:url)

  • Get pgbackup url

    heroku pgbackups:url

  • Restore pg database from a url:

    • NOTE: If you are going to restore a whole database from a dump, it makes sense to first clobber the existing one using heroku pg:reset. You can potentially hit some migratino problems otherwise.

    heroku pgbackups:restore CRIMSON '' --remote staging

  • To drop / reset the database

    heroku pg:reset DATABASE

  • Deleting precompiled assets to force all assets to get precompiled again

    heroku repo:purge_cache -a appname

Node and npm

  • Upgrading npm

    [sudo] npm i -g npm

  • To make sure my local npm files are in alignment with the the files in the respository:

    npm i -g npm
    rm -rf node_modules/
    npm i
    • To install a package to a specific version and update package.json and package-lock.json see following example:
      npm install eslint@4.18.2

    Learn more about --save and --save-dev to make updates locally to node_modules when running the aforementioned command.

    • Audit security issues:
    npm audit

    To fix security issues use

    npm audit fix
    • Running eslint I had trouble running eslint using npm run eslint. I also had trouble runniing it with ./node_modules//bin/eslint . .

    I had to run it using ./node_modules/bin/eslint app/ --ext es6.



  • ls (list methods) in self
  • ls —grep finds specific names
  • cd <object> cds into the object... ie that is the new self.
  • ? (show-doc) Class#method / object.method
  • $ (show-method) Class#method / object.method
  • next (next line without stepping through function calls)
  • step (next line respecting function call)
  • play -l 6 (play line number 6... same as copyig and pasting that line)
  • edit (opens up the editor to edit the file) / edit -m (edit current method)
  • edit <method> edits the specific method
  • try-again (I think that is a part of pry-rescue which re-runs the specific failing? test or rails request)
  • break <method> break on the method
  • break -d 1 disable first breakpoint.
  • up / down (go and and down the call stack)
  • whereami (get information on where you are in the call stack)
  • _ex_ recently raised exception
  • _file_ (last required file)
  • binding.pry open pry within the current binding
  • _ex_.bractrace gives backtrace of the exception
  • wtf gives first five lines of the backtrace
  • wtf??? with increasing question marks gives increasing lines of backtrace.
  • exit-program exit all future breakpoints and the current running process.


  • Find inverse dependencies of a gem gem dependency <gemname> --reverse-dependencie

  • Edit installed gem in bundler

    export BUNDLER_EDITOR=mvim && bundle open gemname

  • List out all the gems that will be updated if you run the bundle update command: bundle outdated

  • clean out all the unrequired gems under certain conditions.

    bundle clean

To read more about it you can try:


  • List all possible rake tasks rake -T

  • To see routes: bundle exec rake routes

  • To list all the middleware bundle exec rake middleware


  • Start the rails server with debugger options

    rails server --debugger

  • To test out some code without changing any data:

    rails console --sandbox Any modifications that are made will be rolled back on exit.

Rails Generators


  • To migrate:

    rake db:migrate

  • To go back one migration:

    rake db:rollback

  • To go back two migrations:

    rake db:rollback STEP=2

  • Adding a column

    rails generate migration AddActiveToNews active:boolean

  • Adding paperclip columns:

    rails generate migration add_paperclip_columns_to_my_model image_file_name:string image_content_type:string image_file_size:integer image_updated_at:datetime

  • Mailers:

To automatically generate mailer and associated directories

rails generate mailer MyMailer


  • Create a gem executible gem build scriptura.gemspec
  • Publish a gem gem push <gem-file-name example gem push scriptura-0.0.3.gem


  • Making an Http get request using tokens:

     HTTParty.get("http://api.local.dg:3000/v0/collections/wjfmvjzo/resources", :query => {"page[number]" => '1', "page[size]" => '366'}, :headers => {'Authorization' => "Token token=\"api-token\""})

Local bootstrap:
Use: FILE=/Users/gagan/projects/desiring-god-new/db/dumps/dg_production_a926_20161228T103557-0600.dump rake db:bootstrap


  • To get the information about all possibilities of using the rvm command:


  • To see a list of installed rubies:

    rvm list; #My terminal does not show the system installed ruby with this command

  • To go to the system installed version of rvm

    rvm system

  • To make system version of ruby default ,

    rvm system --default

  • to uninstall rvm

    rvm implode apparently



Excluding directories in your grep

When it is in the current directory:

grep -r -F "Date" . --exclude-dir={.git,tmp,log,vendor}

When it is in the tree but not the current directory

grep -r -F "Date" . --exclude="*spec/cassettes*"


Only get headers from the url

curl -s -D - -o /dev/null

Only get headers from the url behind http digest auth

curl -s -D - -o /dev/null --digest -u <username>

Then enter password. or try:

curl -s -D - -o /dev/null --digest -u <username>:<password>


Run command multiple times: for i in {1..10}; do commandNameHere; done

find and replace

find and replace recursively within a folder:

perl -p -i -e 's/oldstring/newstring/g' `find ./ -name '*.rb'` or

perl -p -i -e 's/oldstring/newstring/g' `grep -ril oldstring *`

Replace backreference with lower case:

  • \l change the case
  • \L also changes the case

Using a variable to replace existing matching expression

  • Following script changes ResourceType.find('Article), or ResourceType.find('Books') to ResourceType.find('articles') ResourceType.find('books') perl -p -i -e "s/ResourceType.find\('(.)/ResourceType.find('\l\$1/g" spec/redirectors/v_2014/resource_library_spec.rb

  • Following script replaces %r{<something>} to hello(<something>) in lib/scripts
    perl -p -i -e "s/%r\{(.*)}/hello(\$1)/g" lib/scripts/


Repeat command multiple times over

for i in {1..10}; do rspec spec/features/resource_library/sermons_spec.rb; done

Renaming files in a pattern using unix

for f in *worker* ; do mv "$f" "echo $f | sed s/worker/job/"; done

Renaming files in a pattern using ruby
> folder_path = '/Users/gagan/projects/desiring-god-new/app/jobs'
> Dir.glob(folder_path + '/*').each do |f|
>     File.rename(f, folder_path + '/' + File.basename(f).gsub('worker', 'job') + File.extname(f))
> end

Copy to clipboard using pbcopy.

pbcopy < file.txt

Use pbpaste to paste


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.