Useful Command Line Commands

Below represents a list of useful command line commands and tricks that you may not know about. Some of them may even turn out to increase your efficiency as a command line user.

Returning to the previous directory

When using the cd command, you can use the - flag to return you to the previous directory.

$ cd /some/directory
$ cd /another/directory/level
$ cd -
/some/directory

This can be a more useful flag to use as opposed to using .. which will simply cd up one directory level.

Creating nested directories

Passing in the -p flag when using mkdir will created nested directories if they do not exist already.

The below example will create a hello and the nested goodbye directories.

$ mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$ mkdir -p hello/goodbye

Display hidden files and folders

Developers may wish to display hidden files and folders on their OSX/macOS systems. Configuration files such as .htaccess are hidden by default.

However, to show hidden files, you can run the following command.

$ defaults write com.apple.finder AppleShowAllFiles -bool TRUE

Repeat the previous command

To repeat the previous command, you can use a double exclamation mark, !!.

$ mkdir test
$ !!
mkdir test
mkdir: test: File exists

Similarly, you can can use sudo !! to execute the previous command as an administrator.

Mac screenshot formats

When you take a screenshot on OSX/macOS systems, they are saved with the png extension. You can run the following command to change the format of the screenshots to use the jpg extension.

$ defaults write com.apple.screencapture type JPG

Other file formats you can use are PDF and TIFF.

Execute a command after the first one succeeds

To run a command based on whether the previous command completed successfully, you can use && and chain commands together.

$ mkdir some_directory && cd some_directory

Similarly, using || will allow the successive command to execute if the preceding fails.

Checking disk space

To find out the disk space used or remaining space left, use the disk free command, df

$ df
Filesystem    512-blocks      Used Available Capacity iused               ifree %iused  Mounted on
/dev/disk1s1   489825072 214730624 267504264    45% 2568358 9223372036852207449    0%   /

You can display the values in a human readable format by passing in the -h flag.

$ df -h
Filesystem      Size   Used  Avail Capacity iused               ifree %iused  Mounted on
/dev/disk1s1   234Gi  102Gi  128Gi    45% 2568358 9223372036852207449    0%   /

And lastly, to clear any gibberish from your command line output, use the clear command.

$ cd this
$ mkdir that
$ cd the_other
$ clear