Tricks for Git bash on Windows

In this article, you will see some useful Git bash tricks on Windows, like:

  • Keyboard shortcuts

  • Change drive

  • Search command history

  • Open an application

  • Configure SSH

  • Run bash scripts

  • Open a file with Notepad++

  • Speed up commands

Basic keyboard shortcuts and usages for Git bash

Keyboard shortcuts

Move cursor

  • alt+b, back (left) a word.
  • alt+f, forward (right) a word.
  • ctrl + xx, toggle between the start of line and current cursor position.

Delete, copy to clipboard

  • ctrl+u, cut/delete the Line before the cursor to the clipboard.

  • ctrl+k, cut the Line after the cursor to the clipboard.

Process control

  • ctrl+c, interrupt/Kill whatever you are running (SIGINT).
  • ctrl + s, stop output to the screen (for long running verbose commands). Then use PgUp/PgDn for navigation

Basic usages

# Exit Git bash
$ exit

# Clear the terminal
$ clear

# !$ can be used to refer the last argument of the preceding command
$ echo > a.txt
$ cat !$    # equivalent to "cat a.txt"

Change drive in Git bash on Windows

If you want to change to another drive, just take the drive as a directory under root directory like below:

# Change to E:// dirve
$ cd /e

# Chang to a folder under D:// drive
$ cd /d/programs/php/hello-php
$ pwd
/d/programs/php/hello-php

To change to a path which contains special characters like Program Files (x86)/, just quote the folder with ' with the same as what ls shows.

$ ls
'Program Files'/       programs/
'Program Files (x86)'/ projects/

$ cd 'Program Files (x86)'/
# Now you are under 'Program Files (x86)'/

# To change to a path with spaces but no other special characters
$ cd Programs\ Files
# Or
$ cd 'Programs Files'

Another convenient way is typing cd plus a space in Git bash, then drag and drop your target folder inside a Windows Explorer window to the Git bash (After this action the folder’s full path is copied to Git bash), press Enter key.

# Type cd plus a space
$ cd 
# Drag and drop your target folder to Git bash and press Enter key
$ cd /d/programs/php/hello-php

/d/programs/php/hello-php
$

Built-in commands for Git bash on Windows

Git for Windows contains a number of libraries and utilities from the GNU projects and other projects (such as Bash, zlib, curl, tcl/tk, perl, MSYS2). You can find the packaged commands in Git’s /usr/bin and mingw32/bin / mingw64/bin directory.

Below lists some commonly built-in commands, yours may be different depending on your Git bash version.

$ cd
$ curl
$ diff
$ du
$ echo
$ find
$ grep
$ gzip
$ ls
$ mkdir
$ mv
$ perl
$ rm
$ sed
$ where
$ which
...

The newer version comes with subversion.

You can add a new command to Git bash if it misses. See Make Git bash on Windows a better terminal for which commands you can add and how to do that.

Reverse search Git bash command history

ctrl+r

Pressing ctrl+r allows you to reverse search your command history through keywords. Press ctrl+r then input the keywords, it will prompts the found command instantly. If the prompted command is exactly what you want, press enter to execute it directly or press esc to just select the command.

$ (reverse-i-search)`test': np modules/test.php

If the suggested command is not what you want, press ctrl+r repeatedly to cycle backwards through alternatives, or give more keywords to limit the range. If you miss one and want to search forward, press ctrl+s (To enable ctrl+s to search forward history, add stty -ixon to ~/.bash_profile to disable xon/xoff feature which takes ctrl+s).

fzy (a high enhanced tool for ctrl+r , needs extra installation)

If ctrl+r does not meet your needs, fzy is a high enhanced tool compared to ctrl+r. Actually fzy is a general fuzzy finder tool written in go language. It shows an interactive preview of all the possible matches for you to choose. You need to install fzy to use it.

history (a command to manage command history)

# List the command history
$ history
...
101 which firefox
102 which chrome
103 echo > foo.conf
104 cat foo.conf
105 start firefox

# Refer a command with its number in history: !n
$ !105  # it execute "start firefox" command after you hit enter
start firefox

# Find a specific command, pipe history through grep command
$ history|grep -i 'first few letters of command'
# Example:
$ history|grep -i 'cd contente'

See more on history:

History configuration

export HISTCONTROL=erasedups
export HISTSIZE=10000
shopt -s histappend

Open an application in Git bash on Windows

To start an application, use start command, the application does not need to be added to the PATH environment variable.

# Open Chrome browser
$ start chrome
$ start chome bing.com

# Open Firefox in a new window
$ start firefox --new-window

# Open Windows Explorer
$ start explorer
$ start explorer .

Open a file with Notepad++ in Git bash on Windows

To open a file with Notepad++:

# Open ~/.bashrc file
$ start notepad++ ~/.profile

To simplify it, add an alias for this command.

$ echo "alias np='start notepad++'" >> ~/.bashrc

# Source the ~/.bashrc to make the new alias take effect instantly
$ . ~/.bashrc

$ np ~/.profile

Note:

If you use below command in Git bash to open a file with Notepad++ and there is no Notepad++ application already being running, Git bash stays at this command. You can not execute the next command until Notepad++ is closed.

> $ '/c/Program Files (x86)/Notepad++/notepad++.exe' ~/.bashrc
> ```

To create a file and open it with Notepad++:

```shell
$ npnew readme.txt

npnew is a function defined in .bashrc:

function npnew() {
    touch "$1";
    np "$1";
}

Create a new file tells different commands to create a new file. touch is a safer one. If a file with the same name exists already, it will update the timestamps of the file. Other commands like cat, echo , use >> instead of > , i.e. cat >> readme.txt to avoid override existing content if any.

Note:

Depending your Git for Windows version, if it does not read ~/.bashrc automatically in the next time you open Git bash, you can put content ~/.bash_profile instead of ~/.bahsrc or create ~/.bash_profile with below content to make it reads ~/.bashrc.

> if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
> ```

## Start a new  Git bash on Windows

Note starting a Git bash with below methods does not load new environment variable like `PATH`. To make Git bash terminal read the most recent Windows environment variables, start it manually.

### Use Alt+F2 to start a new Git bash

In a Git bash, press `alt+f2` to open a new Git bash terminal.

### Use command to start a new Git bash

Add below function in your `~/.bash_profile`, remember to replace the Git location with your own:

```bash
# Start a Git bash terminal
function gitbash() {
    dir="$PWD";
    cd /c/'Program Files (x86)'/Git/ && start git-bash.exe && cd "$dir";
}

Then you can start a new Git bash in Git bash:

# Make the new .bash_profile take effect instantly in an existing Git bash
$ ~/.bash_profile

# Start a new Git bash terminal
$ gitbash

You may wonder why not use below command, it’s shorter. In fact what it does is not what you expect.

$ start /c/'Program Files (x86)'/Git/git-bash.exe

Output the path that Git bash gets

To print the path that Git bash gets:

$ echo $PATH

Config SSH for Git bash to transfer files between remote and local

Preconditions: You have already a generated SSH key and put the public one on the remote server. The instructions are the same as when you do that for connecting a remote repository over SSH. If you forget, check generating your SSH key.

To configure a remote server for Git bash connecting over SSH, add below content to ~/.ssh/config file. Remember to replace each value with your own ones.

Host my_server
  HostName xx.xx.xx.xx
  Port 22
  User john
  IdentityFile c:\users\john\.ssh\id_rsa

About config options


  • Host, Limits the subsequent declarations are applied for just one or more hosts set in the value.
  • Host name Specifies the real host name to log into. It can be abbreviations for hosts or numeric IP addresses.
  • Port. Defaults to be 22 for SSH protocol.
  • User. The user name on the remote server.
  • IdentityFile Specifies a file from which the user’s identity key is read

There are more options you can configure, like:

  • PasswordAuthentication

Then you can run below command like the remote server being a special drive:

# Copy a file from remote server to local.
$ scp my-server:/home/jane/hello.sh .

To log into the remote server to execute operations on the server:

$ ssh my-server

Set variables for Git bash on Windows

.bash_profile:

# Export a variable in .bash_profile
export DIR=/c/dir

# Add quotes if a variable contains special characters
export ANOTHER_DIR=''/c/Program Files'

Run .sh scripts in Git bash on Windows

To run a .sh script, just run:

# Execute hello.sh script
./hello.sh

You can run a .sh script without a shebang line (the first line starts with #! to specify which program to run the script) , for Git for Windows comes with bash.

echo 'hello';
exit 0;

If this does not work for you, add the shebang line to specify sh.exe program:

#!C:/Program Files (x86)/Git/bin/sh.exe

echo 'hello';
exit 0;

Speed up Git bash on Windows

You may find it takes too long for Git bash to run some commands on Windows. git-speedup provides a bash script which contains a few configuration commands to speed up executing commands on Windows (also works on Mac) likegit status, git add, git pull, git push, ls, cd etc. Below are some examples:

echo "Enable git preload file index"
git config --global core.preloadindex true #Enable git preload file index

echo "Enable Global git cache filesystem "
git config --global core.fscache true #Enable the filesystem cache

echo "Enable Local git cache filesystem "
git config core.fscache true

Note: Some improvement action (such as git config core.ignoreStat true) may come at price. Make sure you know what each command does before you start to use it.

Resources

Git bash

About Git for Windows

Git for Windows is very different from Git in one very important respect: It ships with much more than any other Git distribution: As Windows does not provide the POSIX (Portable Operating System Interface) infrastructure Git expects, Git for Windows always had to ship with much more than any other Git distribution: provide a bash, a perl, many POSIX tools such as sed, awk, tr, etc.

Relationships between Git for Windows, MSYS2, Cygwin

At first, Git for Windows just packages all the required tools as-are.

Later, MSYS2 started, it already provided most of the tools needed. It turned out to just get and modify MSYS2 to Git for Windows (That’s Git for Windows 2.x).

Concepts

  • Cygwin (an Unix style terminal on Windows, with more build tools)

    It is a large collection of GNU and Open Source tools which provide functionality similar to a Linux distribution on Windows.

  • MSYS2 (essentially a bare-minimum version of Cygwin)

    It is a collection of tools and libraries providing you with an easy-to-use environment for building, installing and running native Windows software.

  • mingw-get, a package manger (from MinGW project). MSYS2 provides it.

Git for Windows wiki FAQ

  • Default terminal

    Git for Windows defaults to using mintty terminal.

  • Excel file modifications not always noticed.

    Git uses the modified time field of files to quickly detect changes. Rather Excel used the change time field. Git will notice the modifications if a git status is performed.

  • Git bash configuration files

Git bash configuration file syntax

Git bash environment variables: Git bash’s configuration file uses regular bash syntax, see more on Bash configurations files.

Which configuration file Git bash reads

Git bash does not read .bashrc automatically in newer version(at least v2.5 does not). In newer versions of Git for Windows, Bash is started with --login which causes Bash to not read .bashrc directly. Instead it reads .bash_profile.

If this file does not exist, create it with the following content:

  if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

In etc/profile.d/bash_profile.bash under Git (v2.13.2), you can see that Git bash needs .bash_profile to run .bashrc:

  # add ~/.bash_profile if needed for executing ~/.bashrc
  if [ -e ~/.bashrc -a ! -e ~/.bash_profile -a ! -e ~/.bash_login -a ! -e ~/.profile ]; then
    printf "\n\033[31mWARNING: Found ~/.bashrc but no ~/.bash_profile, ~/.bash_login or ~/.profile.\033[m\n\n"
    echo "This looks like an incorrect setup."
    echo "A ~/.bash_profile that loads ~/.bashrc will be created for you."
    cat >~/.bash_profile <<-\EOF
  	# generated by Git for Windows
  	test -f ~/.profile && . ~/.profile
  	test -f ~/.bashrc && . ~/.bashrc
  	EOF
  fi

Bash

  • Bash syntax

  • Bash menu

    • Redirection

    • Bash variables

    • Bash built-in commands

    alias, bind, builtin, caller, command, declare, echo, enable, help, let, local, logout, mapfile, printf, read, readarray, source, type, typeset, ulimit, unalias

SSH

Others

August 6, 2020 cmd git-bash

A universal document converter -- Pandoc

Pandoc is a powerful document conversion tool, it is called swiss-army knife in this field. It understands many document formats, like markdown, ms word, pdf, html, etc. And it is free, you may install it as a command tool or try it online.

cmd dev

A tool showing cheatsheet for programming languages and Linux commands

cheat.sh is a pretty useful tool that provides a cheat sheet for all you need like Linux commands, programming languages and DBMSes. You can use it to display usages of a Linux command, a code snip of a programming language like code for looping an array with PHP. For the moment, it covers 56 programming languages(C, awk, bash, PHP, Python, Perl, R, Ruby, JS, Go, Swift...) and 1000+ Linux commands.

cmd dev git-bash

Unix style terminals for Windows

If you need to run commands on Windows, it would be a much better choice to use an Unix style terminal to replace default Windows console. Here it introduces some good of them, like Git for Windows, Cmder, and a more powerful one Cygwin.

cmd