Conventions
# - requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ - requires given linux commands to be executed as a regular non-privileged user
How to change the prompt in terminal?
user@host:~/path/to/current-dir$ export PS1='$ '
$
$
Useful Command Line Utility Tools
To print last N commands form Terminal:
$ history N
Using the history command - Media Temple
The output is command history in form:
2000 sudo apt install ipython ipython-notebook
2001 sudo apt list --installed | grep python3-pip
2002 sudo apt list --installed | grep python3-dev
...
To copy only commands (without command number) keep CTRL+ALT pressed and select desired text columns and rows with left mouse click button.
To shorten some long command: How to Create and Use Alias Command in Linux
To list current aliases:
$ alias
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
Operating System
How to find what's the version of the installed OS:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 18.04.3 LTS
Release: 18.04
Codename: bionic
User management
Linux User Management | My Public Notepad
File and Directory Ownership and Permissions
Working with directories
To list the content of the directory:
ls
To list directories in the current directory, names only, and each name in its own line:
$ ls -1d *
-1 list one file per line
-d list directories themselves, not their contents
* list all items in the current directory (they might be filtered by other flags, like -d)
To list all files (including hidden) in the current directory:
ls -a
$ ls target_directory
Example:
$ ls /usr/local/go/
To list directories and files in form of a tree install tree package:
$ sudo apt install tree
...and use it as e.g.:
$ tree -I *node*
-I = ignores directories that match given pattern
To diff two directories use:
$ diff -r dir1 dir2
This shows which files are only in dir1 and those only in dir2 and also the changes of the files present in both directories if any. If any file does not end with a newline character, this will be reported as well:
$ diff -r dir1 dir2
diff -r dir1/test.txt dir2/test.txt
1c1
< First line in dir1/test.txt
\ No newline at end of file
---
> First line in dir2/test.txt
\ No newline at end of file
Binary files /dir1/test.bin and /dir2/test.bin differ
Only in /dir1/subdir1/: subsubdir1
Only in /dir2/subdir1/: file.zip
---What does 1c1 in diff tool mean?
1c1 indicates that line 1 in the first file was c hanged somehow to produce line 1 in the second file.
They probably differ in whitespace (perhaps trailing spaces, or Unix versus Windows line endings?).
man diff
Difference between two directories in Linux [closed]
How to make diff check a symlink link itself?
diff reports two files differ, although they are the same!
man cmp
diff reports two files differ, although they are the same!
man cmp
To find the location of some directory starting from the root directory (/) use:
$ find / -type d -name dir_name
What does the suffix .d (in directory name) mean in Linux? - Server Fault
Time and Date
To convert Unix time to human readable, use:
$ date -d @1583944041
Wed 11 Mar 16:27:21 GMT 2020
Working with files in Linux | My Public Notepad
Package management
apt (Advanced Packaging Tool) - It is not a command itself but a package which contains set of tools which manage installation and removal of other packages.
apt-get
apt-get update - downloads the package lists from the repositories and "updates" them to get information on the newest versions of packages and their dependencies. It will do this for all repositories and PPAs.
http://askubuntu.com/questions/222348/what-does-sudo-apt-get-update-do
apt-cche
add-apt-repository - adds a repository to the list of repositories
To apply latest security updates on Ubuntu:
sudo apt-get update
sudo apt-get -y upgrade
Difference Between apt and apt-get Explained
Should I use apt or apt-get?
You might be thinking if you should use apt or apt-get. And as a regular Linux user, my answer is to go with apt.
apt is the command that is being recommended by the Linux distributions. It provides the necessary option to manage the packages. Most important of all, it is easier to use with its fewer but easy to remember options.
I see no reason to stick with apt-get unless you are going to do specific operations that utilize more features of apt-get.
How to add repository to Apt sources?
For application named app:
$ sudo install -m 0755 -d /etc/apt/keyrings
$ sudo curl -fsSL https://download.app.com/linux/debian/gpg -o /etc/apt/keyrings/app.asc
$ sudo chmod a+r /etc/apt/keyrings/app.asc
# Add the repository to Apt sources:
$ echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/app.asc] https://download.app.com/linux/debian \
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/app.list > /dev/null
-----------------------------------------------------------------------------------------------------------------------
To download a file into some specific directory:
cd /dest_dir
wget https://example.com/archive_file.tar.gz
To install a package/software in Ubuntu, it is usually enough to copy it to /usr/local directory.
To move dir1 to some other location e.g. /usr/local use:
mv new_app /usr/local
To move dir1 to some other location e.g. /usr/local use:
mv new_app /usr/local
Linux Directories
Unix Filesystem Hierarchy | My Public NotepadInstalling Software on Linux | My Public Notepad
Working with Archive files
Tar Format
To unpack the .tar.gz in the current directory use:
$ tar -zxvf archive_file.tar.gz
-x = extract
-f (--file) = use archive file; this flag has to be the last in the list of flags and to be followed by the archive file name
-v (--verbose) = verbose output
-z (--gzip, --gunzip, --ungzip) = filter the archive through gzip
To unpack only the specific directory from the archive use:
$ tar -zxvf archive_file.tar.gz dir_name
To unpack archive to the specific directory:
$ tar -zxvf archive_file.tar -C path/to/dest_dir
-C (--directory) stands for "Change to directory"
Example:
$ tar -xzf go1.12.1.linux-amd64.tar -C /usr/local
$ sudo tar -xzvf Postman-linux-x64-7.5.0.tar.gz -C /opt
Why compressed directories cannot be extracted in /opt?
$ sudo apt-get install rar unrar
then go to the directory where all x.party.rar files are and execute:
$ unrar x -e file.part1.rar
ZIP format
Zip one subdirectory ( e.g. ./modules/foo) while traversing it recursively (-r), but exclude (-x) some its subdirectories and files (on MacOS we need to put paths with wildcards under quotes):
% zip -r module-foo.zip \
./modules/foo \
-x "./modules/foo/.terraform/*" \
-x ./modules/foo/.terraform.lock.hcl
Unzipping into the specified directory:
$ unzip bookmarks.zip -d bookmarks-dev-413
$ unzip bazel-1.2.1-dist.zip -d bazel bazel-1.2.1-dist
Unzip files in particular directory or folder under Linux or UNIX - nixCraft
$ unzip bookmarks.zip -d bookmarks-dev-413
$ unzip bazel-1.2.1-dist.zip -d bazel bazel-1.2.1-dist
Unzip files in particular directory or folder under Linux or UNIX - nixCraft
Networking
Introduction to Linux Networking | My Public NotepadHardware management
To verify if you're running a 64-bit system use GNU Core Utility: uname.
Swap Memory Management
To check virtual memory statistics (the latest reading) use:
$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
0 0 138816 9157820 1739872 11514740 0 1 1559 366 102 64 26 7 66 0 0
$ vmstat 1
To disable and then reenable swap:
$ sudo swapoff -a
$ sudo swapon -a
performance - How to empty swap if there is free RAM? - Ask Ubuntu
Displays/Monitors Management
$ xrandr --listmonitors
Monitors: 2
0: +*HDMI-1 2560/677x1440/381+0+0 HDMI-1
1: +eDP-1 1920/344x1080/193+112+1440 eDP-1
To see details for the current display:
$ xrandr --current
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
eDP-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 344mm x 193mm
1920x1080 60.03*+ 60.01 59.97 59.96 59.93 48.02
1680x1050 59.95 59.88
1600x1024 60.17
1400x1050 59.98
1600x900 59.99 59.94 59.95 59.82
...
360x202 59.51 59.13
320x180 59.84 59.32
HDMI-1 disconnected (normal left inverted right x axis y axis)
DP-1 disconnected (normal left inverted right x axis y axis)
HDMI-2 disconnected (normal left inverted right x axis y axis)
DP-2 disconnected (normal left inverted right x axis y axis)
HDMI-3 disconnected (normal left inverted right x axis y axis)
$ ls /dev/video*
To check the number of processors:
$ grep -c ^processor /proc/cpuinfo | sed 's/^0$/1/'
4
To see details for all processors:
$ cat /proc/cpuinfo
To list CPU architecture information, use lscpu. E.g.
$ lscpu | grep "Byte Order"
Byte Order: Little Endian
SSH
How to generate SSH key pair on Ubuntu
How to test SSH key password on Ubuntu
---
To get base64 encoding of a string:
$ echo -n my_string | base64
or
$ printf my_string | base64
---
TBC...
How to get the GPU info?
lshw = list hardware
-C = class
$ sudo lshw -C display
*-display UNCLAIMED
description: 3D controller
product: GM107GLM [Quadro M620 Mobile]
vendor: NVIDIA Corporation
physical id: 0
bus info: pci@0000:01:00.0
version: a2
width: 64 bits
clock: 33MHz
capabilities: pm msi pciexpress bus_master cap_list
configuration: latency=0
resources: memory:ee000000-eeffffff memory:d0000000-dfffffff memory:e0000000-e1ffffff ioport:e000(size=128) memory:ef000000-ef07ffff
*-display
description: VGA compatible controller
product: Intel Corporation
vendor: Intel Corporation
physical id: 2
bus info: pci@0000:00:02.0
version: 04
width: 64 bits
clock: 33MHz
capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
configuration: driver=i915 latency=0
resources: irq:130 memory:ed000000-edffffff memory:c0000000-cfffffff ioport:f000(size=64) memory:c0000-dffff
NVidia and Intel in same Laptop: which card is used?
---
To get base64 encoding of a string:
$ echo -n my_string | base64
or
$ printf my_string | base64
---
TBC...
Getting Information about Hardware
How to get the GPU info?
lshw = list hardware
-C = class
$ sudo lshw -C display
*-display UNCLAIMED
description: 3D controller
product: GM107GLM [Quadro M620 Mobile]
vendor: NVIDIA Corporation
physical id: 0
bus info: pci@0000:01:00.0
version: a2
width: 64 bits
clock: 33MHz
capabilities: pm msi pciexpress bus_master cap_list
configuration: latency=0
resources: memory:ee000000-eeffffff memory:d0000000-dfffffff memory:e0000000-e1ffffff ioport:e000(size=128) memory:ef000000-ef07ffff
*-display
description: VGA compatible controller
product: Intel Corporation
vendor: Intel Corporation
physical id: 2
bus info: pci@0000:00:02.0
version: 04
width: 64 bits
clock: 33MHz
capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
configuration: driver=i915 latency=0
resources: irq:130 memory:ed000000-edffffff memory:c0000000-cfffffff ioport:f000(size=64) memory:c0000-dffff
NVidia and Intel in same Laptop: which card is used?
$ lspci -k | grep -EA2 'VGA|3D'
00:02.0 VGA compatible controller: Intel Corporation Device 591b (rev 04)
Subsystem: Dell Device 07a9
Kernel driver in use: i915
--
01:00.0 3D controller: NVIDIA Corporation GM107GLM [Quadro M620 Mobile] (rev a2)
Subsystem: Dell GM107GLM [Quadro M620 Mobile]
Kernel modules: nvidiafb, nouveau
GNU Bash Shell Commands
To determine the default shell for the current user:
$ echo "$SHELL"
/bin/bash
/bin/bash
or print the name of the current terminal process:
$ echo $0
bash
bash
Robert Muth: Better Bash Scripting in 15 Minutes
Bash script should start with shebang e.g.
#!/bin/bash
---
Escaping and preserving special characters in bash
Bash wildcards: ? (question mark) and * (asterisk) | LinuxG.net
What is the meaning of a question mark in bash variable parameter expansion as in ${var?}? - Stack Overflow
shell - Expansion of variable inside single quotes in a command in Bash - Stack Overflow
linux command line find escape question mark - Server Fault
---
What does 'cd $_' mean?
$_ expands to the last argument to the previous simple command* or to previous command if it had no arguments. Typical use:
mkdir dirA && cd $_
---
To see all Bash commands, execute:
$ help
---
$ help set
set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
Set or unset values of shell options and positional parameters.
Change the value of shell attributes and positional parameters, or
display the names and values of shell variables.
Options:
-a Mark variables which are modified or created for export.
-b Notify of job termination immediately.
-e Exit immediately if a command exits with a non-zero status.
-f Disable file name generation (globbing).
-h Remember the location of commands as they are looked up.
-k All assignment arguments are placed in the environment for a
command, not just those that precede the command name.
-m Job control is enabled.
-n Read commands but do not execute them.
-o option-name
Set the variable corresponding to option-name:
allexport same as -a
braceexpand same as -B
emacs use an emacs-style line editing interface
errexit same as -e
errtrace same as -E
functrace same as -T
hashall same as -h
histexpand same as -H
history enable command history
ignoreeof the shell will not exit upon reading EOF
interactive-comments
allow comments to appear in interactive commands
keyword same as -k
monitor same as -m
noclobber same as -C
noexec same as -n
noglob same as -f
nolog currently accepted but ignored
notify same as -b
nounset same as -u
onecmd same as -t
physical same as -P
pipefail the return value of a pipeline is the status of
the last command to exit with a non-zero status,
or zero if no command exited with a non-zero status
posix change the behaviour of bash where the default
operation differs from the Posix standard to
match the standard
privileged same as -p
verbose same as -v
vi use a vi-style line editing interface
xtrace same as -x
-p Turned on whenever the real and effective user ids do not match.
Disables processing of the $ENV file and importing of shell
functions. Turning this option off causes the effective uid and
gid to be set to the real uid and gid.
-t Exit after reading and executing one command.
-u Treat unset variables as an error when substituting.
-v Print shell input lines as they are read.
-x Print commands and their arguments as they are executed.
-B the shell will perform brace expansion
-C If set, disallow existing regular files to be overwritten
by redirection of output.
-E If set, the ERR trap is inherited by shell functions.
-H Enable ! style history substitution. This flag is on
by default when the shell is interactive.
-P If set, do not resolve symbolic links when executing commands
such as cd which change the current directory.
-T If set, the DEBUG and RETURN traps are inherited by shell functions.
-- Assign any remaining arguments to the positional parameters.
If there are no remaining arguments, the positional parameters
are unset.
- Assign any remaining arguments to the positional parameters.
The -x and -v options are turned off.
Using + rather than - causes these flags to be turned off. The
flags can also be used upon invocation of the shell. The current
set of flags may be found in $-. The remaining n ARGs are positional
parameters and are assigned, in order, to $1, $2, .. $n. If no
ARGs are given, all shell variables are printed.
Exit Status:
Returns success unless an invalid option is given.
---
What is the difference between [] and [[]]?
Bash Brackets Quick Reference
Test if a command outputs an empty string
if [[ $(ls -A) ]]; then
echo "there are files"
else
echo "no files found"
fi
---
Create a directory if this does not exist:
Bash script should start with shebang e.g.
#!/bin/bash
---
Escaping and preserving special characters in bash
Bash wildcards: ? (question mark) and * (asterisk) | LinuxG.net
What is the meaning of a question mark in bash variable parameter expansion as in ${var?}? - Stack Overflow
shell - Expansion of variable inside single quotes in a command in Bash - Stack Overflow
linux command line find escape question mark - Server Fault
---
$_
What does 'cd $_' mean?
mkdir dirA && cd $_
---
To see all Bash commands, execute:
$ help
---
set
$ help set
set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
Set or unset values of shell options and positional parameters.
Change the value of shell attributes and positional parameters, or
display the names and values of shell variables.
Options:
-a Mark variables which are modified or created for export.
-b Notify of job termination immediately.
-e Exit immediately if a command exits with a non-zero status.
-f Disable file name generation (globbing).
-h Remember the location of commands as they are looked up.
-k All assignment arguments are placed in the environment for a
command, not just those that precede the command name.
-m Job control is enabled.
-n Read commands but do not execute them.
-o option-name
Set the variable corresponding to option-name:
allexport same as -a
braceexpand same as -B
emacs use an emacs-style line editing interface
errexit same as -e
errtrace same as -E
functrace same as -T
hashall same as -h
histexpand same as -H
history enable command history
ignoreeof the shell will not exit upon reading EOF
interactive-comments
allow comments to appear in interactive commands
keyword same as -k
monitor same as -m
noclobber same as -C
noexec same as -n
noglob same as -f
nolog currently accepted but ignored
notify same as -b
nounset same as -u
onecmd same as -t
physical same as -P
pipefail the return value of a pipeline is the status of
the last command to exit with a non-zero status,
or zero if no command exited with a non-zero status
posix change the behaviour of bash where the default
operation differs from the Posix standard to
match the standard
privileged same as -p
verbose same as -v
vi use a vi-style line editing interface
xtrace same as -x
-p Turned on whenever the real and effective user ids do not match.
Disables processing of the $ENV file and importing of shell
functions. Turning this option off causes the effective uid and
gid to be set to the real uid and gid.
-t Exit after reading and executing one command.
-u Treat unset variables as an error when substituting.
-v Print shell input lines as they are read.
-x Print commands and their arguments as they are executed.
-B the shell will perform brace expansion
-C If set, disallow existing regular files to be overwritten
by redirection of output.
-E If set, the ERR trap is inherited by shell functions.
-H Enable ! style history substitution. This flag is on
by default when the shell is interactive.
-P If set, do not resolve symbolic links when executing commands
such as cd which change the current directory.
-T If set, the DEBUG and RETURN traps are inherited by shell functions.
-- Assign any remaining arguments to the positional parameters.
If there are no remaining arguments, the positional parameters
are unset.
- Assign any remaining arguments to the positional parameters.
The -x and -v options are turned off.
Using + rather than - causes these flags to be turned off. The
flags can also be used upon invocation of the shell. The current
set of flags may be found in $-. The remaining n ARGs are positional
parameters and are assigned, in order, to $1, $2, .. $n. If no
ARGs are given, all shell variables are printed.
Exit Status:
Returns success unless an invalid option is given.
set -x
- enables a mode of the shell where all executed commands are printed to the terminal.
- typically used for debugging
What is the difference between [] and [[]]?
Bash Brackets Quick Reference
Test if a command outputs an empty string
if [[ $(ls -A) ]]; then
echo "there are files"
else
echo "no files found"
fi
---
Create a directory if this does not exist:
DATA_DIR=data-vol
if [ -d ${DATA_DIR} ]; then
echo Directory ${DATA_DIR} exists.
else
echo Directory ${DATA_DIR} does not exist.
echo Creating directory ${DATA_DIR} ...
mkdir ${DATA_DIR}
fi
or, as one-liner:
[ -d path/to/mydir ] || mkdir -p path/to/mydir
(-p option instructs mkdir to create all intermediate parent directories to mydir)
Semicolon in conditional structures
The semicolon is needed only when the end of line is missing:
if [ "a" == "a" ] ; then echo "true" ; fi
Without semicolons, you get Syntax error.
---
How to capture exit code of the application most recently executed in Terminal?
$ echo $?
It can also be used in a bash script, e.g.:
ginkgo -r
if [[ $? != 0 ]]; then
echo "Unit tests failed. Terminating build process..."
exit 1
fi
---
Variables
$ dependencies=(build-essential cmake pkg-config libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libxvidcore-dev libavresample-dev python3-dev libtbb2 libtbb-dev libtiff-dev libjpeg-dev libpng-dev libtiff-dev libdc1394-22-dev libgtk-3-dev libcanberra-gtk3-module libatlas-base-dev gfortran wget unzip)
We can print the array:
$ echo ${dependencies[@]}
build-essential cmake pkg-config libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libxvidcore-dev libavresample-dev python3-dev libtbb2 libtbb-dev libtiff-dev libjpeg-dev libpng-dev libtiff-dev libdc1394-22-dev libgtk-3-dev libcanberra-gtk3-module libatlas-base-dev gfortran wget unzip
We can print elements with specific indexes in the array:
$ echo ${dependencies[0]}
$ echo ${dependencies[1]}
---
No comments:
Post a Comment