The Advent of CLI - Day 2

Getting Started

OK, so you popup your terminal window and there a blank rectangle
stare at you and you’re not sure of what this thing can do or how you can work with it …


First thing first

Or how do you even start that terminal window?


Under Windows

  • simply click the Windows Terminal shortcut icon thingy
  • but huho you probably get a blue window, that’s the PowerShell
    and not the shell we want to use for now (but Microsoft try to make that your default)
  • at the top of the Windows Terminal
    click the “down arrow” or V and select “Ubuntu 18.04” or maybe just “Ubuntu”
  • from that point you should be under the Bash shell of WSL (Windows Subsystem for Linux)

First you need to learn to configure the Windows Terminal
read Editing Windows Terminal JSON Settings

You would want

  • set the defaultProfile to the GUID of “Ubuntu 18.04”
    eg.

    "defaultProfile" : "{58ad8b0c-3ef8-5f4d-bc6f-13e4c00f2530}",
    "initialCols" : 120,
    "initialRows" : 50,
    "requestedTheme" : "system",
    "keybindings" : []
    ...
    
  • set the startingDirectory of your “Ubuntu 18.04” to the home directory
    eg.

    {
        "name": "Ubuntu-18.04",
        "commandline" : "wsl -d Ubuntu-18.04",
        "startingDirectory" : "//wsl$/Ubuntu-18.04/home/<Your Ubuntu Username>",
    }
    

From now on, it should always open by default to the Bash shell of Ubuntu 18.04 in WSL.


Under macOS

  • simply click the Terminal.app in /Applications/Utilities
  • by default you should be under a Bash shell

If you want you can change the theme, color, etc.
by going into Terminal > Preferences > Text

either pick an already existing theme or define yours

You can learn more here Change General preferences in Terminal on Mac


Note: for macOS Catalina

here we can read

macOS Catalina still has the same /bin/bash (version 3.2.57) as Mojave
and earlier macOS versions. This change is only for new accounts created
on macOS Catalina. When you upgrade to Catalina, a user’s default shell will remain what it was before.

so if you are under this case of new account under Catalina, you will have to change your shell to bash, read How to Change the Default Shell to Bash on macOS Catalina

also by using bash as your default shell you might encounter an annoying warning as explained here

Users that have /bin/bash as their default shell on Catalina will see a prompt
at the start of each Terminal session stating that zsh is now the recommended default
shell. If you want to continue using /bin/bash, you can supress this message by
setting an environment variable in your .bash_profile or .bashrc.

export BASH_SILENCE_DEPRECATION_WARNING=1


Under Linux Ubuntu

If you need to customise the colors etc.
read for ex: How to Customize the Terminal in Ubuntu


The Basic

Usually when you start a shell you end up in your home directory and from there you can, among many other things, navigate the file system by using various commands

  • you send a command to the shell (command line interpreter)
    by directly typing after the command-prompt $
    for ex: $ echo "hello world" and then you hit [ENTER]
  • it is assumed you input command to the shell
    line by line then followed by the key [ENTER] for each line,
    I will not write [ENTER] each time you have to type it

Note:
$ to indicate a command prompt
[ENTER] represent the key ‘enter’ on your keyboard
[CTRL] + [w] represent a combinaison of keys on your keyboard (‘control’ and ‘w’)
<arg> for a mandatory argument
[arg] for an optional argument

  • echo [message] - display a message
    eg. you echo something to the terminal
    $ echo "something here"
  • pwd - print working directory
    will show the current path where you are
    for ex: $ pwd
  • ls [path] - list
    list the file and directory
    if no argument [path] provided list what’s in your current directory
    • . one dot is a “shortcut” to the current directory
    • .. two dots is a “shortcut” to the parent directory
  • cd <path> - change directory
    will change the current path to another one
    the <path> can be relative or absolute
    • $ cd .. navigate to the parent directory
  • touch <name> - create a file
    for ex: $ touch hello.txt
  • mkdir <name> - create (make) a directory
    for ex: $ mkdir world
  • rm <path> - remove a file
    for ex: $ rm hello.txt
  • rmdir <path> - remove a directory
    for ex: $ rmdir world

All those commands are small binaries installed on the system,
to know their path you could use the command which

for ex: $ which mkdir
will output “/bin/mkdir” (the absolute path of the binary)

In fact, when I say binaries, those are full blown command-line programs
which most of the time accept numerous parameters, to know more you can
use another command man (for “manual”) to display the different parameters/options/etc.
available to a particular program

for ex: $ man mkdir

under macOS the output will look like

MKDIR(1)                  BSD General Commands Manual                 MKDIR(1)

NAME
     mkdir -- make directories

SYNOPSIS
     mkdir [-pv] [-m mode] directory_name ...

DESCRIPTION
     The mkdir utility creates the directories named as operands, in the order specified, using mode rwxrwxrwx (0777) as modified by the current umask(2).

     The options are as follows:

     -m mode
             Set the file permission bits of the final created directory to the specified mode.  The mode argument can be in any of the formats specified to the chmod(1)
             command.  If a symbolic mode is specified, the operation characters ``+'' and ``-'' are interpreted relative to an initial mode of ``a=rwx''.

     -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each operand must already exist.  On the other hand,
             with this option specified, no error will be reported if a directory given as an operand already exists.  Intermediate directories are created with permission
             bits of rwxrwxrwx (0777) as modified by the current umask, plus write and search permission for the owner.

     -v      Be verbose when creating directories, listing them as they are created.

     The user must have write permission in the parent directory.

DIAGNOSTICS
     The mkdir utility exits 0 on success, and >0 if an error occurs.

SEE ALSO
     rmdir(1)

COMPATIBILITY
     The -v option is non-standard and its use in scripts is not recommended.

STANDARDS
     The mkdir utility is expected to be IEEE Std 1003.2 (``POSIX.2'') compatible.

HISTORY
     A mkdir command appeared in Version 1 AT&T UNIX.

BSD                            January 25, 1994                            BSD

under Linux the output will look like

MKDIR(1)                       User Commands                           MKDIR(1)

NAME
       mkdir - make directories

SYNOPSIS
       mkdir [OPTION]... DIRECTORY...

DESCRIPTION
       Create the DIRECTORY(ies), if they do not already exist.

       Mandatory arguments to long options are mandatory for short options too.

       -m, --mode=MODE
              set file mode (as in chmod), not a=rwx - umask

       -p, --parents
              no error if existing, make parent directories as needed

       -v, --verbose
              print a message for each created directory

       -Z     set SELinux security context of each created directory to the default type

       --context[=CTX]
              like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX

       --help display this help and exit

       --version
              output version information and exit

AUTHOR
       Written by David MacKenzie.

REPORTING BUGS
       GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
       Report mkdir translation bugs to <http://translationproject.org/team/>

COPYRIGHT
       Copyright © 2017 Free Software Foundation, Inc.  License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
       This is free software: you are free to change and redistribute it.  There is NO WARRANTY, to the extent permitted by law.

SEE ALSO
       mkdir(2)

       Full documentation at: <http://www.gnu.org/software/coreutils/mkdir>
       or available locally via: info '(coreutils) mkdir invocation'

GNU coreutils 8.28             January 2018                            MKDIR(1)

So let me give you the straight dope on all this

  • yes, it will take time to learn many little commands and sometimes their parameters till you feel comfortable
  • yes, most of those commands are similar but they can also be slightly different
    • first, many of those commands are directly related to their C function
      see mkdir
      #include <sys/stat.h>
      int mkdir(const char *path, mode_t mode);
      
      or see _mkdir, _wmkdir
      int _mkdir(
         const char *dirname
      );
      int _wmkdir(
         const wchar_t *dirname
      );
      
    • second, the standard part is POSIX
      The Portable Operating System Interface
    • third, the non-standard parts can still exists
      between macOS, different distribution of Linux, BSD, etc.
  • yes, you’re not only learning the command-line you’re also learning a bit of C (and some system calls)
  • yes, for now it seems much more complicated and lengthy to type something like
    $ cd ../../stuff/music/va/Hideki Naganuma/Black Hot Vodka/BLACK HOT VODKA-346744644.mp3
    then just navigate in few clicks in a file browser, but it will get better (it is not useless, I promise)

I could list a lot of commands etc. but others have already done that so here few tutorials

Example:
you search “howto check disk space on the command-line”
and the first link is How To Check Disk Space On Linux From The Command Line
where you learn everything about df and du etc.


The number of commands you will know by heart will mostly depends on the type of work you do in the command-line, and how long you spend time using those commands, different commands will work “about the same” but with different features, you might end up preferring using command A instead of command B, at the end you will find your own style.


Shortcuts

It is about text input, so the same way you can go faster knowing shortcuts in GUI programs, you can also do the same knowing shortcuts to manipulate text.

see Effective Shell Part 1: Navigating the Command Line
and Moving efficiently in the CLI
and 13 Linux Terminal Shortcuts Every Power Linux User Must Know

also check the Readline shortcuts

here the details

1. Tab

This is the Linux shortcut you cannot live without. It will save you so much time in the Linux command line.

Just start typing a command, filename, directory name or even command options and hit the tab key. It will either automatically complete what you were typing or it will show all the possible results for you.

If you could only remember one shortcut, this would be the chosen one.

2. Ctrl + C

These are the keys you should press in order to break out of a command or process on a terminal. This will stop a running program immediately.

If you want to stop using a program running in the foreground, just press this key combination.

3. Ctrl + Z

This shortcut will send a running program in the background. Normally, you can achieve this before running the program using the & option but if you forgot to do that, use this key combination.

4. Ctrl + D

This keyboard shortcut will log you out of the current terminal. If you are using an SSH connection, it will be closed. If you are using a terminal directly, the application will be closed immediately.

Consider it equivalent to the ‘exit’ command.

5. Ctrl + L

How do you clear your terminal screen? I guess using the clear command.

Instead of writing C-L-E-A-R, you can simply use Ctrl+L to clear the terminal. Handy, isn’t it?

6. Ctrl + A

This shortcut will move the cursor to the beginning of the line.

Suppose you typed a long command or path in the terminal and you want to go to the beginning of it, using the arrow key to move the cursor will take plenty of time. Do note that you cannot use the mouse to move the cursor to the beginning of the line.

This is where Ctrl+A saves the day.

7. Ctrl + E

This shortcut is sort of opposite to Ctrl+A. Ctrl+A sends the cursor to the beginning of the line whereas Ctrl+E moves the cursor to the end of the line.

Note: If you have the Home and End keys on your keyboard, you can also use them. Home is equivalent to Ctrl +A and End is equivalent to Ctrl + E.

8. Ctrl + U

Typed a wrong command? Instead of using the backspace to discard the current command, use Ctrl+U shortcut in the Linux terminal. This shortcut erases everything from the current cursor position to the beginning of the line.

9. Ctrl + K

This one is similar to the Ctrl+U shortcut. The only difference is that instead of the beginning of the line, it erases everything from the current cursor position to the end of the line.

10. Ctrl + W

You just learned about erasing text till the beginning and the end of the line. But what if you just need to delete a single word? Use the Ctrl+W shortcut.

Using Ctrl+W shortcut, you can erase the word preceding to the cursor position. If the cursor is on a word itself, it will erase all letters from the cursor position to the beginning of the word.

The best way to use it to move the cursor to the next space after the targetted word and then use the Ctrl+W keyboard shortcut.

11. Ctrl + Y

This will paste the erased text that you saw with Ctrl + W, Ctrl + U and Ctrl + K shortcuts. Comes handy in case you erased wrong text or if you need to use the erased text someplace else.

12. Ctrl + P

You can use this shortcut to view the previous command. You can press it repeatedly to keep on going back in the command history. In a lot of terminals, the same can be achieved with PgUp key.

13. Ctrl + N

You can use this shortcut in conjugation with Ctrl+P. Ctrl+N displays the next command. If you are viewing previous commands with Ctrl+P, you can use Ctrl+N to navigate back and forth. Many terminals have this shortcut mapped to the PgDn key.

Bonus shortcut: Ctrl + R to search in command history

You typed some command but cannot remember what it was exactly? Meet Ctrl + R.

This keyboard shortcut allows you to perform a search in your command history. Just press Ctrl+R and start typing. It will show the last command that matches the string you typed. Note that the typed string could be anywhere in the command. How cool is that?

If you want to see more commands for the same string, just keep pressing Ctrl + R.

You can press enter to run the command selected or press Esc to come out of the search with the last search result.

Try it and be amazed.

yes be amazed lol :smiley:

you don’t have to know all those shortcuts by heart, learn maybe one or two, then learn some more over time etc.


From that point, you should be able to discover any command (google search, tutorials, whatever…), find out a bit of their documentation, and be comfortable entering text in the terminal.

1 Like