User Tools

Site Tools


text:linux-cli

Linux Command Line Interface

My friend asked me about some tutorial or “cheat sheet” on Linux command line interface. A goal is to explain basics for people who came to Linux from other, mostly GUI oriented operating systems.

When you log into remote server via ssh, or invoke a terminal app on local Linux machine, you get a command line prompt, like this:

  $ _

It's a prompt from the command line shell.

To quit from the current shell, use command:

  exit

Shell versions

When troubleshooting, it's important to know which exacly shell you are using. There are a few different shell applications in Linux. On most Linuxes and on Mac, the default interactive shell is Bash (/bin/bash). On Ubuntu the default shell /bin/sh is Dash (/bin/dash), for efficiency reasons. To quickly check which version you are logged in, use command “ps $$”. It replaces $$ with a process ID of the current shell, and shows the details. In case of Bash, you will see “-bash” as the application name:

  $ ps $$
      PID TTY      STAT   TIME COMMAND
     3011 pts/0    Ss     0:00 -bash

In case of Dash, you will see /bin/sh:

  $ ps $$
      PID TTY      STAT   TIME COMMAND
     3011 pts/0    Ss     0:00 /bin/sh

Other shells are also available, like tcsh, ksh, zsh and others. But most people use bash, so I will assume it from now on.

My Choice: Bash Commander

As for my taste, I prefer shells with “visual” navigation, in a style of famous Norton Commander. My personal choice is Bash Commander. It's essentially the same Bash, extended with a capability to display two windows and navigate through filesystem with cursor keys.

Bash Commander can be installed from Github: https://github.com/sergev/bash-commander

Environment Variables

When Bash starts, it reads the environment variables from file ~/.bashrc. Here ~ means your home directory. Usually .bashrc file already exists for you, pre-installed by your system admin. You can explore it by using “less” utility:

  $ cd ~
  $ less .bashrc

The less utility allows to browse a text file and scroll it forward and backward with PageDown/PageUp keys and down/up arrows.

Note that .bashrc is used only by interactive non-login shells. For login shells other files are used, like /etc/profile, ~/.bash_profile, ~/.bash_login, and ~/.profile. If you cannot find where some environment variable is configured in your .bashrc, look at the above files. For all details of Bash configuration, see the manual page:

  man bash

The manual pages are available for all other CLI commands, for example:

  man less

or

  man man

To see all the envirinment variables, use:

  env

The most important variable is PATH. It's a list of directories to search for commands, separated by colon. To show a value of a particular variable, use echo:

  echo $PATH

To change value of (global) variable, use:

  export NAME=value

The assignment “=” sign is important here, and there must be no spaces around it. For example:

  export EDITOR=/usr/bin/nano

By convention, the EDITOR variable is used by many Linux commands when they need to invoke a text editor for you to modify some file. By default, “vi” editor is used, and it causes a lot of trouble for most inexperienced users. So I recommend to set EDITOR to something more friendly, like the Nano editor. Nano is typically pre-installed on most Linuxes, and it has pretty intuitive interface. For example, to exit Nano, ^X is used.

Prompt

The default Bash prompt is boring. It can be easily enhanced by modifying the PS1 variable. Here is the value I use on all my Linux accounts:

  PS1="\[\033[44m\](\h) \W\[\033[m\033[1m\] \\\$\[\033[m\] "

This looks frightening, but fear not! Most of ugly stuff there is about colors. Two fields are important: \h means the host name, and \W is the basename of the current directory. Just put this line into your ~/.bashrc file and re-load it:

  $ cd ~
  $ source .bashrc

It's easier to explain on example. Say when I log into my server sergev.org and go to directory /website/pages, the prompt becomes like this:

  (sergev) pages $

So from the prompt I can see on which server and at which directory I am right now.

History

In Bash, every command entered by user is stored to the History buffer. This buffer has a large size, typically 1000 lines, and is preserved across login sessions. To browse the list, use the history command, for example:

  $ history
    210  grep export .bashrc
    211  ls -l /usr/bin/*
    212  man nano
    213  grep alias .bashrc
    214  man netstat
    215  traceroute somewhere.net

Any line from the history can be repeated by number prefixed with ! symbol. Say, let's repeat the “man nano” command:

  !212

Previous command can be repeated as:

  !!

Also you can use the Up and Down arrows to browse through the History buffer. Any previous command line can be edited and run again.

Parameters from the previous command also are available via the ! prefix. For example, !$ means the

  $ traceroute somewhere.net
  traceroute to somewhere.net (3.33.152.147), 30 hops max, 60 byte packets
  ...
  $ ping !$
  ping somewhere.net
  ...

To search for command in the History buffer, use ^R. For example, let's search for the previous man command. Type ^R and enter “man”. The prompt becomes:

  (reverse-i-search)`man': man tail

Press Enter to execute, or ^R to continue searching, or ^C to cancel.

Aliases

Bash allows to define short names for commonly used commands. Here is a list of shortcuts I define in my ~/.bashrc script:

  alias h=history
  alias _='stty sane'
  alias ls='ls --color=auto'
  alias grep='grep --color=auto'
  alias df='df -m -x squashfs -x tmpfs -x devtmpfs'

Instead of typing “history” every time, I prefer to shorten it as just “h”.

Command “_” helps to quickly restore the terminal modes in case it's corrupted by some previous command.

Commands “ls” and “grep” can colorize the output. I redefine them as aliases to enable colors by default.

For “df” command I disable temporary filesystems, so the output includes only real disks.

To browse your aliases, use:

  alias

Cheat Sheet

Here is a list of frequently used Linux commands, with brief comments.

  cd dir

Enter the specified directory.

  ls

List files.

  pwd

Print the name of the current (working) directory. The same name is available as the environment variable PWD. It can be displayed with the echo command:

  echo $PWD

Browsing Files

  cat file.txt

Display file contents to the standard output. It works fine for short files. For longer files better use the less command:

  less file.txt

It displays one page of the text file. You can navigate via the contents with PageDown/PageUp keys or Down/Up arrows.

  head file.txt

Show the first 10 lines of the file.

  tail

Show the last 10 lines of the file.

  grep pattern file.txt

Search text files for a string (or pattern).

  diff old.txt new.txt

Compare two files and highlight the differences between them.

  find . -name '*foo*'

Search current directory tree for a file with given name.

Exploring the System

  ps auxww

Display information about the active processes.

  top

Display active processes and kernel info in interactive mode. Type 'i' to hide idle processes. Use 'q' to stop.

  df

Report file system disk space usage.

  free

Display amount of free and used memory in the Linux system.

  finger

Display information about the system users.

  groups

Print the groups a user is in. It is important to know your groups, as your access to the system services depends on it.

  uname --all

With –all option, print the following system information:

  • kernel name
  • network node hostname
  • kernel release
  • kernel version
  • machine hardware name
  • processor type
  • hardware platform
  • operating system
  w

Show who is logged on and what they are doing.

  whoami

Print the user name associated with the current effective user ID.

  sudo command

Execute any command as the superuser. To be able to do it, the administrator should include you into the list of 'sudoers'.

For example:

  sudo lshw | less

Extract detailed information on the hardware configuration of the machine.

Modifying the Files

  chmod +w file.txt

Change file access mode.

  chown vak /home/vak

Change file owner.

  mkdir /mnt/media

Create a directory.

  mv old new

Move (rename) files.

  cp -a file new-copy

Copy files. With -a option, the whole file tree is copied recursively, with all attributes preserved (including modification time).

  kill 123

Kill the given process ID by sending a signal to it.

  killall nano

Kill a process by name.

  passwd

Change user password.

Networking

  ip addr

Display information about your IP address.

  netstat -lt

Show network information: options -lt mean to see the listening TCP/IP sockets. The netstat utility can do much more. Visit https://linuxhint.com/install-netstat-command-linux/ for details.

  ping somewhere.net

Send network packets to the remote device to make sure it is alive.

  traceroute somewhere.net

Send network packets to the remote device and count the hops from router to router as packets make their way via the network.

  curl -O https://www.keycdn.com/img/example.jpg

Download a file from remote server.

  ssh somewhere.net

Log into remote device.

References

text/linux-cli.txt · Last modified: 2022/07/02 21:00 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki