Command line (Unix)

Commands tips and examples:

bash tips

Configuration

Conserver la configuration d'iptables lors des démarrages

Il est nécéssaire de relancer ce script à chaque modifications d'iptables

Gestion des services

(must be executable: chmod +x /etc/init.d/blah)

Define when service have to be start or stop:

To remove from the startup sequence

  • https://help.ubuntu.com/community/UbuntuBootupHowto

  • http://www.debian-administration.org/articles/28

  • man update-rc.d

  • http://en.wikipedia.org/wiki/Runlevel

  • http://www.debuntu.org/how-to-managing-services-with-update-rc-d/

  • List all runlevel for the service apache2: ls -l /etc/rc?.d/*apache2

User prompt

  • http://www.tldp.org/LDP/Bash-Beginners-Guide/html/Bash-Beginners-Guide.html#sect_08_02_01

User management

Network

Note: ifconfig, route, mii-tool, nslookup commands are obsolete

/etc/hostname /etc/hosts

Windows networking

Note: samba is the package that provides all this windows specific networking support

HTTP

How to display request headers with command line curl - Stack Overflow

wget

Multi purpose download tool

SSH Tunnel

Backup external server

Use rsync if possible, or lftp, curl, wget, scp, sftp. See also unison, bacula or amanda

Copy files over SSH

Copy files over SSH shell

Copy files with sftp

Copy files with lftp

/dst/dir.lftp:

--exclude / -x use extended regular expression (see egrep) \.nfo. Folders path don't start with slash, but have a trailing slash: etc/bin/

Add --reverse to restore backup

For lftp –> Fatal error: Certificate verification: Not trusted:

Copy files from FTP with wget

Use a .wgetrc file to store configuration

/dst/dir.wget:

Note: if you set password in URL don't forget to encode special chars: mypass#gh647 to mypass%23gh647

Copy files with rsync

Network efficient file copier

Use the --dry-run option for testing

Resources for exclude metadata and system files:

Math

Date and clock

Locale

Packages

RPM Packages ( Fedora, Red Hat and like):

YUM packages tool (Fedora, RedHat and alike):

DEB packages (Debian, Ubuntu and like):

APT packages tool (Debian, Ubuntu and alike):

Pacman packages tool (Arch, Frugalware and alike):

Monitoring and debugging

System

System information

See also sysinfo.

Power management

Aka shutdown, restart and logout of a system

Interactive

See also linux keyboard shortcuts

Shell

Command-line interface (CLI), not for graphical user interface (GUI)

The default shell is defined for a specific user by the file /etc/passwd

In /etc/bashrc or ~/.bashrc

Shells:

Shell config

Profile files, defined by (in order, but also if the shell is interactive and/or a login):

  1. (global system) /etc/profile

  2. (global system) /etc/bashrc

  3. (user) ~/.bash_profile

  4. (user) ~/.bash_login

  5. (user) ~/.profile

  6. (user) ~/.bashrc (not used by some OS like macOS for login shell, it's recommended to if [ -s ~/.bashrc ]; then source ~/.bashrc; fi in ~/.profile for that case)

  7. (user) ~/.bash_logout au logout

(and /etc/bash.bashrc, /etc/bash.bashrc.local?)

To reload a configuration file (here the file ~/.bashrc)

initialisation at the session level (.bash_profile) and initialisation at each shell level (.bashrc)

By convention, the prompt ends with $ for users and by # for root

Command alias

Programmable bash completions

See complete buildin command

Terminal history auto complete

In ~/.inputrc or /etc/inputrc:

  • http://www.gnu.org/software/bash/manual/html_node/Readline-Init-File.html

  • https://stackoverflow.com/questions/1030182/how-do-i-change-bash-history-completion-to-complete-whats-already-on-the-line

On OSX Page up and Page down in Terminal are by default use to manipulat buffer instead to send key stroke

You can change it in Preferences → Settings → Keyboard:

  • Page down : \033[6~

  • Page up : \033[5~

  • End : \033OF (works in vi, vim, etc.) ou \033[4~, \033[F, \005

  • Home : \033OH (works in vi, vim, etc.) ou \033[1~, \033[H, \001

Use esc to type these strings (add \033 in input field) or past (via the context menu)

Shell variables

See also arrays

Colors and control sequences

For ls colors:

key=effect;foreground colour;background colour separated by :.

Ex.: a symlink bright pink ln=01;95;40 give:

To known color config:

Mouse position and click

Aka mouse tracking escape sequences

Command arguments

Command alias

A ajouter dans ~/.bashrc

Shell script file

Note: take care editing bash scripts

Create a shell script file.sh the execute the following command to allow it to be executable:

Start with the shebang #!/bin/sh, which indicate the script interpreter (sh, php, python, perl, node, etc.) or for portability, use env:

Or detect the right interpreter with an additional line, here to use nodejs or node. : command in bash is noop.

To include shell script into an other:

Shell script syntax

Use $( ), and don't use `` anymore: Bash FAQ 82.

Avoid using UPPERCASE variable names. That namespace is generally reserved by the shell for special purposes (like PATH), so using it for your own variables is a bad idea.

Escape special char in argument:

Wildcard files:

File Wildcards

Brace expansion

Strings:

Shell parameter expansion:

Redirection

File pointer and file redirection

Bash support process substitution:

Is similar to: echo hello > file; cat file; rm file

$(cat file) is same as $(< file)

Here-doc & here-string:

File descriptors (fd) :

  • 0 is stdin IN

  • 1 is stdout OUT

  • 2 is stderr ERROR

2>&1 redirects fd 2 to 1 (stderr to stdout)

Pipe:

Network with redirection

Use instead specialized tools like netcat or socat

Fork process

Execute in background

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell

Add a bin folder to global executables

Pour éviter de tapper le chemin entier vers les commandes / executables

Pour l'ajouter de façon permanente, l'écrire dans ~/.profile ou ~/.bashrc

Automatic error detection

Instead || exit 1 after each important command.

Dotfiles

Tree navigation

Files and folders operations

File name:

Using sed or other external processes to do simple string operations like stripping extensions and prefixes is inefficient. Instead, use parameter expansions which are part of the shell (no external process means it will be faster). Some helpful articles on the subject are listed below:

Bash FAQ 73: Parameter expansions Bash FAQ 100: String manipulations

File listing and searching

Find support shell pattern for -path and -ipath parameters:

Find missing files

Find duplicates files

Remove duplicates

Rdfind – redundant data find:

BTRFS Deduplication - btrf Wiki

See also diff -q --binary or cmp -s $1 $2 && echo "identical" || echo "different"

Then replace files by hardlink

Find files by content

Find corrupted files

Find files with 100 consecutive zero bytes (partially downloaded, etc.)

Note: If you get grep: invalid repetition count(s), use (\x00\x00\x00\x00){250,} instead of \x00{1000,} (because repetition as limitation)

Delete files and directories

Aka remove files and dirs

Copy or move files and directories

Aka duplicate and rename

On macOS install it with port port install p5-file-rename (but should use the cmd rename-5.22 where 22 is installed version via port instead of rename) or brew brew install rename

Archives and compressed files

Create archive from file list:

Split files

FAT32 maximum file size is "4 GiB minus 1 byte" (4294967295 bytes)

To write file with a size larger than that limit, you need to split it.

In destination folder, execute following command:

(the part example.dmg.part. will be used to name output files like example.dmg.part.aa, example.dmg.part.ab and so on)

Read write race condition

Choose incremental filename

Test if dirB/file.ext exist else choose dest file name as dirB/file-1.ext, if already exist choose dirB/file-2.ext and so one

File attributes

File type

Supported formats are listed by:

  • files in /etc/magic

  • /etc/magic.mime

  • /usr/share/misc/magic.mgc

  • /usr/share/file/magic.mgc

  • /opt/local/share/misc/magic.mgc

  • files in /opt/local/share/misc/magic

  • ~/.magic.mgc

  • ~/.magic

The extension of compiled magic: *.mgc

Files permissions

Name, extension and parent folder

Note: Don't use parameter substitution, it's not work with all cases

Read file content or stream

Create or truncate a file

File comparaisons

Note: you can export LANG=C for speed. Also these assume no duplicate lines within a file

Use diff and patch

Compare 2 folders:

Sans -q mais avec -u pour faire un patch

Et sans prendre en compte les fichiers metadonnées d'OSX et de Windows, le tout ordonné :

Comparer 2 files:

Apply a patch:

Use heredoc

Use -p1 to strip path a/ and b/

Folder bind

Aka folder link, like symlink but for folder (standart implementation don't allow to link folder)

The mount point is registerd in /etc/fstab as fs-type: bind

Archives and compression

Incremental listing

Incrementaly add/changed/delete files (list made from cron or similar)

Change encoding

Use recode that obsoletes iconv, dos2unix, unix2dos

Temporary file

Prefix a list of paths

If sed pattern come from variable, some escaping is needed: sed "s/$BRE/$REPL/"

Instead use awk with variables:

Change file in-place

Or sponge

Do not use echo "$( jq '.address = "abcde"' test.json )" > test.json, this will not always work. Large files it will cause issues, also with whitespaces, non-printable and escapment sequences. Never redirect a file to itself, it is always a bad idea.

See also Temporary file

Relative path

Text operations

Aka text processing

Sed

Aka stream editor

Note: sed uses stdin and stdout. Newer versions support inplace editing with the -i option

Remove multiline comment:

See also:

Search an replace in files

AWK

AWK reads the input a line at a time. A line is scanned for each pattern in the program, and for each pattern that matches, the associated action is executed.

Disk and file system operations

Backup the filesystem

Format a filesystem:

Filesystem swap:

Disk space

See also FSlint

Clone disk

Aka duplicate disks

For supported partitions (on source drive), use Disk Utility

For not supported partitions

Clone exact disk (boot sector, all partitions & data, etc.) to an other drive (to a file, use a path to a file instead of /dev/sdX, see this page for other options like split the image and dd man page for partial copy etc.)

For disk use /dev/sdX (or /dev/hdX, or BSD /dev/diskX or even /dev/rdiskX for better speed)

Change bs to find the optimal value. 64K seem a good value, but it's related to hardware and software (USB2.0 to USB2.0 RAID). Try to use the same value as the disk cache 8388608 size, or the block size 4096.

With bs=64K:

  • USB 2.0 to USB 2.0: 20 to 11 MB/s

  • SATA 3.0 (3.0 Gb/s) to SATA 3.0 (3.0 Gb/s): 130 MB/s

CDs

And DVDs, CD images

Command operations

Command help

Aka man, command documentation

Section numbers of the man manual:

  1. executable programs or shell commands

  2. system calls (functions provided by the kernel)

  3. library calls (functions within program libraries)

  4. special files (usually found in /dev)

  5. file formats and conventions eg /etc/passwd

  6. games

  7. miscellaneous (including macro packages and conventions), e.g. man(7), groff(7)

  8. system administration commands (usually only for root)

  9. kernel routines (non standard)

Some commands support also (or instead) an option that show the help, could be:

  • --help

  • -h

  • help

  • -?

  • /?

SSH

Aka Secure SHell

To disallow SSH remote root login, in /etc/ssh/sshd_config update/add:

SSH Keyfile

In ~/.ssh/config:

Convert PDF 1.4

Force version

Email local spool

/var/spool/mail/$USER

UUID

Last updated

Was this helpful?