Command line (Unix)
Commands tips and examples:

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.dhttp://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
sftpCopy files with lftp
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:
https://linux.die.net/man/1/lftp
http://mewbies.com/lftp_basic_usage_tutorial.htm
Copy files from FTP with wget
wgetUse 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
rsyncNetwork efficient file copier
Use the --dry-run option for testing
Resources for exclude metadata and system files:
https://github.com/github/gitignore
https://github.com/joeblau/gitignore.io/tree/master/data
https://gist.github.com/keithmorris/c652b2a4d88788e5416d
https://github.com/dotphiles/dotphiles/blob/master/git/gitignore
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:
Bash (Unix shell) - Wikipedia - Bourne-Again shell
Shell config
Profile files, defined by (in order, but also if the shell is interactive and/or a login):
(global system)
/etc/profile(global system)
/etc/bashrc(user)
~/.bash_profile(user)
~/.bash_login(user)
~/.profile(user)
~/.bashrc(not used by some OS like macOS for login shell, it's recommended toif [ -s ~/.bashrc ]; then source ~/.bashrc; fiin~/.profilefor that case)(user)
~/.bash_logoutau 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
terminal - Why doesn't .bashrc run automatically? - Ask Different - add
if [ -s ~/.bashrc ]; then source ~/.bashrc; fito~/.bash_profileSuggestion: disambiguate shell setup steps · Issue #351 · Schniz/fnm - About macOS that doesn't source
~/.bashrcUnix shell - Wikipedia - Configuration files
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,\005Home :
\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
named pipe (
mkfifo)
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
stdinIN1 is
stdoutOUT2 is
stderrERROR
2>&1 redirects fd 2 to 1 (stderr to stdout)
man -P less\ +/^REDIRECTION bashhttp://www.tldp.org/LDP/Bash-Beginners-Guide/html/Bash-Beginners-Guide.html#sect_08_02_03_02
/usr/include/unistd.hhttp://en.wikipedia.org/wiki/File_descriptor
Pipe:
Network with redirection
Use instead specialized tools like netcat or socat
/dev/tcp/<host>/<port>and/dev/udp/<host>/<port>{ echo -e "GET / HTTP/1.0\r\nHost: www.example.com\r\n\r" >&3; cat <&3 ; } 3<> /dev/tcp/www.example.com/80bash - /dev/tcp listen instead of nc listen - Unix & Linux Stack Exchange - port listing is not possible
GitHub - caquino/redis-bash: REDIS-BASH - Bash library to access Redis - Example of what can be made with network redirection
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
sedor 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:
*/file.ext*.ext*/file.*
unix - Appending new lines to multiple files - Super User - How to use
echo "test" >> {}within find exec
Find missing files
Find duplicates files
Remove duplicates
BTRFS Deduplication - btrf Wiki
See also diff -q --binary or cmp -s $1 $2 && echo "identical" || echo "different"
centos - What's the quickest way to find duplicated files? - Unix & Linux Stack Exchange
Replace the use of md5sum with
difforcmp: How do I do a binary diff on two identically sized files under Linux? - Super User
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
http://www.cyberciti.biz/faq/linux-bash-delete-all-files-in-directory-except-few/
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.mgcfiles 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
tmp - How create a temporary file in shell script? - Unix & Linux Stack Exchange - See example with file descriptor, which is cleaned automatically
Mktemp with suffix/extension | Gawen's blog - Use temp dir instead of temp 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.
Awk-Batteries/csv.awk at master · Nomarian/Awk-Batteries - parse CSV
gawk -f "$AWK/Units/csv.awk" -e '{print NF}'
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:
executable programs or shell commands
system calls (functions provided by the kernel)
library calls (functions within program libraries)
special files (usually found in /dev)
file formats and conventions eg /etc/passwd
games
miscellaneous (including macro packages and conventions), e.g.
man(7),groff(7)system administration commands (usually only for root)
kernel routines (non standard)
Some commands support also (or instead) an option that show the help, could be:
--help-hhelp-?/?
SSH
Aka Secure SHell
To disallow SSH remote root login, in /etc/ssh/sshd_config update/add:
SSH Keyfile
In ~/.ssh/config:
SSH Configurations - Tower Help - Connecting & Authenticating
Convert PDF 1.4
Force version
Email local spool
/var/spool/mail/$USER
UUID
Last updated
Was this helpful?