Bash Command Line Hacking

Your terminal experience and preferences might lead you to choose a different shell than Bash. However, wheter it is Bash, Zsh, or another variant, they share commonalities that date back to the original Bourne shell sh.

To determine which shell is currently running on your system, try:

> echo $SHELL

Common shells are:

The Bourne shell is the foundation and precursor to many modern command-line interfaces, making it still worth studying today. The following commands refer to Bash and use the shebang #!/bin/bash.

Alternatively the shebang allows you to pass one argument after the interpreter. #! interpreter [optional-one-arg-only] You can use the /usr/bin/env command in combination with bash or rather with another interpreted script. To change the shell options within your env or session you can use the set command.

Parameter Expansion

String fromatting is a common task. To capitalize your stirng, make the first letter a capital letter. You can use the caret sign. Two caret signs make the string to all upper case.

> echo ${USER^}      # caret symbol
> echo ${USER^^}     # caret symbol

Slicing is zero index based and also allows for reverse extraction.

> echo ${USER: -3:2}

Command Substitution

Command subsitution executes the for example the ‘date’ command and captures its output as a string.

$(date)

In general, using $() is a convenient way to execute external commands within Bash scripts or interactive shells.

Arithmetic Expansion

Use the command line as basic calcualtor.

> x=4
> y=2
> echo $((x + y))    # <- no need for $ signs

For arbitrary precission calculation use the basic calculator bc.

> echo "scale=2; 5/3" | bc

Tilde Expansion

The tilde expansion helps with navigating the working directories.

> echo ~
> echo $HOME

To get the home directory of a specific user do this:

> echo ~username

The + and - signs allow you to navigate between the current and previous working directories. The following two commands are the same.

> echo $PWD $OLDPWD
> echo $~+ $~-

Brace Expansion

To generate strings which share a prefix or suffix you can use the brace expansion on a range list. This can be useful for files and folder creation.

> echo {1..10}
1 2 3 4 5 6 7 8 9 10
> echo {1..10..2}    # step size of two
1 3 5 7 9
> echo month{1..10..2}
month1 month3 month5 month7 month9

Quoting

If you want to use a reserved character like ‘&’ you must use one of these escape or quote options.

  • \ gets the literal value of the next character
  • '' single quotes take the text as raw (note: changed from “singel” to “single”).
  • "" double quotes keeps the literal meaning, but allows $, `` (backtick), and \ to be

For example, escape the ampersand for background jobs with a backslash.

> echo John & Johnna    # without escaping
> echo John \& Johnna   # with escaping using a backslash

Use the backslash to get a literal backslash.

> echo "C:\Users\\$USER\Documents"