Conserver la configuration d'iptables lors des démarrages
# Sauvegarde de la configuration d'iptables dans un fichieriptables-save>/etc/iptables.conf# Création d'un fichier sh dans le dossier ...echo"#!/bin/sh">/etc/network/if-up.d/iptables# ... qui restaurera les règles sauvegardé dans le fichier /etc/iptables.confecho"iptables-restore < /etc/iptables.conf">>/etc/network/if-up.d/iptables# Rendre executable le script bashchmod+x/etc/network/if-up.d/iptables
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)
#! /bin/sh# /etc/init.d/blah## BEGIN INIT INFO# Provides: blah# Required-Start: $local_fs $syslog $remote_fs dbus# Required-Stop: $local_fs $syslog $remote_fs# Default-Start: 2 3 4 5# Default-Stop: 0 1 6# Short-Description: Start blah## END INIT INFO# Some things that run alwaystouch/var/lock/blah# Carry out specific functions when asked to by the systemcase"$1"instart)echo"Starting script blah"echo"Could do more here" ;;stop)echo"Stopping script blah"echo"Could do more here" ;;*)echo"Usage: /etc/init.d/blah {start|stop}"exit1 ;;esacexit0
# Set deadline for user passwordchage-E2005-12-31user1# Create a new groupgroupadd [group]# Delete a groupgroupdel [group]# Rename a group from moon to sungroupmod-nmoonsun# Check correct syntax and file format of `/etc/group` and groups existencegrpck# Log into a new group to change default group of newly created filesnewgrp- [group]# Change passwordpasswd# Change a user password (only by root)passwduser1# Check correct syntax and file format of `/etc/passwd` and users existencepwck# Create a new user `user1` belongs `admin` groupuseradd-c"User Linux"-gadmin-d/home/user1-s/bin/bashuser1# Create a new useruseradduser1# Delete a user (`-r` eliminates home directory)userdel-ruser1# Change user attributes as description, group and otherusermod-c"User FTP"-gsystem-d/ftp/user1-s/bin/nologinuser1# Show user rights on filesls-l# or, but show folders "." and ".."ls-all# User informationsidUSERNAME# Show last logs of userslastlog# Show last logged userslast# Show current userwho-a# Command history~/.bash_history~/.history# for root user/root/.bash_history# Be sure no user can hide his command history (a = append only, i = immutable)chattr+a/home/user/.bash_historychattr+i/home/user/.profile# See also# http://www.akyl.net/securing-bashhistory-file-make-sure-your-linux-system-users-won%E2%80%99t-hide-or-delete-their-bashhistory# http://zero202.free.fr/bash/html/ar01s01.html#id336074# https://en.wikipedia.org/wiki/Chattrchattrchwonchmod
Network
Note: ifconfig, route, mii-tool, nslookup commands are obsolete
# Show status of ethernet interface eth0ethtooleth0#Manually set ethernet interface speedethtool--changeeth0autonegoffspeed100duplexfull# Show link status of `eth0`mii-tooleth0# Show configuration of an ethernet network cardifconfigeth0# Configure IP Addressifconfigeth0192.168.1.1netmask255.255.255.0# Configure `eth0` in promiscuous mode to gather packets (sniffing)ifconfigeth0promisc# Show status of wireless interface eth1iwconfigeth1# Manually set wireless interface speediwconfigeth1rate1Mb/sfixed# List wireless networks in rangeiwlistscan# Disable an interface `eth0`ifdowneth0# Activate an interface `eth0`ifupeth0# List network interfaces and their statusiplinkshow# Rename interface eth0 to waniplinksetdeveth0namewan# Bring interface eth0 up (or down)iplinksetdeveth0up# List addresses for interfacesipaddrshow# Add (or del) ip and mask (255.255.255.0)ipaddradd1.2.3.4/24brd+deveth0# List routing tableiprouteshow# Set default gateway to 1.2.3.254iprouteadddefaultvia1.2.3.254# Show routing tableroute-n# Configure default gatewayrouteadd-net0/0gwIP_Gateway# Configure static route to reach network `192.168.0.0/16`routeadd-net192.168.0.0netmask255.255.0.0gw192.168.1.1# Remove static routeroutedel0/0gwIP_gateway# Lookup DNS ip address for name or vice versahostexample.com# Machine namehostname# Lookup local ip address (equivalent to host `hostname`)hostname-i# Active interface `eth0` in dhcp modedhclienteth0# List network services on a system and their PIDnetstat-tupl# List active network connections to/from system and their PIDnetstat-tup# Show routing table alike "route -n"netstat-rn# Show all HTTP traffictcpdumptcpport80# DNS recorddigexample.com# Lookup whois info for hostname or ip addresswhoisexample.com# Activate ip routing temporarilyecho"1">/proc/sys/net/ipv4/ip_forward# Reverse DNSping-a8.8.8.8nslookup-type=ptr8.8.8.8nslookupwww.example.com# Test if remote port is opennc-vzexample.com80nmap-p80example.comtelnetexample.com80timeout1bash-c"</dev/tcp/example.com/80"&&echoPortopen||echoPortclosed
Note: samba is the package that provides all this windows specific networking support
# Find windows machines. See also findsmbsmbtree# Find the windows (netbios) name associated with ip addressnmblookup-A1.2.3.4# List shares on windows machine or samba serversmbclient-Lwindows_box# Show remote shares of a windows hostsmbclient-Lip_addr/hostname# Mount a windows sharemount-tsmbfs-ofmask=666,guest//windows_box/share/mnt/share# Send popup to windows machine (off by default in XP sp2)echo'message'|smbclient-Mwindows_box# Mount a windows network sharemount-tsmbfs-ousername=user,password=pass//WinClient/share/mnt/share# Netbios name resolutionnbtscanip_addr# Netbios name resolutionnmblookup-Aip_addr# Like wget can download files from a host windows via smbsmbget-Rrsmb://ip_addr/share
HTTP
# Get headerscurl-s-D-https://example.com-o/dev/null# Raw bodycurl-s--ignore-content-length--rawhttps://example.com# Get HTTP responseecho-en"GET /feed/ HTTP/1.1\r\nHost:example.com\r\nUser-Agent:Firefox\r\n\r\n"|ncinfoheap.com80# Get the header Content-Typeecho-en"GET /feed/ HTTP/1.1\r\nHost:example.com\r\nUser-Agent:Firefox\r\n\r\n"|nclocalhost80|head-n30|grep-aContent-Type# Search if test is in first 1000 bytes (include header)echo-en"GET /feed/ HTTP/1.1\r\nHost:example.com\r\nUser-Agent:Firefox\r\n\r\n"|nclocalhost80|head-c1K|grep-atest# Get body lengthecho-e"GET / HTTP/1.1\r\nHost: example.com\r\nAccept-Encoding: gzip, deflate\r\n\r\n"|nclocalhost80|sed':a;N;$!ba;s/^.*\r\n\r\n//g'|wc-c# Get body uncompressed length (should be gzipped)echo-e"GET / HTTP/1.1\r\nHost: example.com\r\nAccept-Encoding: gzip, deflate\r\n\r\n"|nc93.184.216.3480|sed':a;N;$!ba;s/^.*\r\n\r\n//g'|gzip-d|wc-c# Simple HTTP serverecho-e"GET / HTTP/1.1\r\nHost:example.com\r\nUser-Agent:Firefox\r\n\r\n"|ncexample.com80>response.httpwhiletrue; donc-l8000<response.http; done# Create `.htpasswd` filehtpasswd-c/path/.htpasswdUSERNAME
# Store local browsable version of a page to the current dir(cddir/&&wget-nd-pHEKkhttp://www.pixelbeat.org/cmdline.html)# Continue downloading a partially downloaded file (with the ability to stop the download and resume later)wget-chttp://www.example.com/large.file# Download a set of files to the current directorywget-r-nd-np-l1-A'*.jpg'http://www.example.com/dir/# FTP supports globbing directlywgetftp://remote/file[1-9].iso/# Process output directlywget-q-O-http://www.pixelbeat.org/timeline.html|grep'a href'|head# Download url at 1AM to current direcho'wget url'|at01:00# Do a low priority download (limit to 20KB/s in this case)wget--limit-rate=20kurl# Check links in a filewget-nv--spider--force-html-ibookmarks.html# Efficiently update a local copy of a site (handy from cron)wget-mhttp://www.example.com/wget-m-U""http://example.com/path/dir
SSH Tunnel
# Redirect local port to a remote machinessh-NfL8080:127.0.0.1:0808user@host
# Copy content of a directory on remote directory via ssh( cd/tmp/local/&&tarc. ) |ssh-Cuser@ip_addr'cd /home/share/ && tar x -p'# Copy a local directory on remote directory via ssh( tarc/home ) |ssh-Cuser@ip_addr'cd /home/backup-home && tar x -p'
Copy files with sftp
sftp-i/path/to/private/keyfileremote.host.tld
Copy files with lftp
/dst/dir.lftp:
set ftp:list-options -a
#set cmd:fail-exit true
# To use keyfile
# http://www.adminschoice.com/how-to-configure-ssh-without-password
# ssh-keygen -t rsa -f keyfile -N ""
#set sftp:connect-program "ssh -a -x -i <keyfile>"
open -u user,pass sftp://sftp.dc0.gpaas.net
mirror --verbose --delete --parallel=4 --only-newer --exclude ^snapshots/ --exclude ^vhosts/ --exclude ^lamp0/\.config --exclude ^lamp0/var/admin/gandi.cnf$ --exclude ^lamp0/var/admin/logrotate.conf$ --exclude ^lamp0/var/cron/admin/logrotate$ --exclude ^lamp0/var/cron/admin/phpsess$ --exclude ^lamp0/db/ --exclude ^lamp0/var/log/.+ --exclude ^lamp0/var/php/www/.+ "${SRC_DIR}" "${DST_DIR}"
exit
# For paths in variables used in sed, see https://stackoverflow.com/a/29613573/470117SRC_DIR=/src/dir; DST_DIR=/dst/dir; sed-e"s#\${SRC_DIR}#$SRC_DIR#"-e"s#\${DST_DIR}#$DST_DIR#"/dst/dir.lftp|lftp-f/dev/stdin
# Synchronization between directoriesrsync-rogpav--delete/home/tmp# Rsync via SSH tunnelrsync-rogpav-essh--delete/homeip_address:/tmp# Synchronize a local directory with a remote directory via SSH and compressionrsync-az-essh--deleteip_addr:/home/public/home/local# Synchronize a remote directory with a local directory via SSH and compressionrsync-az-essh--delete/home/localip_addr:/home/public# Copy as archive (oneway, for backup)rsync-ausername@www.mydomain.tld://dst/dirrsync-r-t-v/path/srcdir/path/destdirrsync-r-t-v/path/srcdirremote:~/My\ documents# Escape spaces, and keep special char interpreted at the destination. See "How to rsync over ssh when directory names have spaces - Unix & Linux Stack Exchange" https://unix.stackexchange.com/questions/104618/how-to-rsync-over-ssh-when-directory-names-have-spacesDEST="~/My\ documents"; rsync-r-t-v/path/srcdir"remote:${DEST///\\ }"# Only get diffs. Do multiple times for troublesome downloadsrsync-Prsync://rsync.server.com/path/to/filefile# Locally copy with rate limit. It's like nice for I/Orsync--bwlimit=1000fromfiletofile# Mirror web site (using compression and encryption)rsync-az-essh--delete~/public_html/remote.com:'~/public_html'# Synchronize current directory with remote onersync-auz-esshremote:/dir/.&&rsync-auz-essh.remote:/dir/date=$(date+%Y%m%d-%H%M)#[for loop over users]older=( $backups/$user/*(N/om) )rsync--archive--recursive \--fuzzy--partial--partial-dir=$backups/$user/.rsync-partial \--log-file=$tempfile--link-dest=${^older[1,20]} \--files-from=$configdir/I-$user \--exclude-from=$configdir/X-$user \ $user@$from:/ $backups/$user/$date/# Copy folder to folder (if mounted)rsync -ah --progress --exclude='$RECYCLE.BIN' --exclude='$Recycle.Bin' --exclude='.AppleDB' --exclude='.AppleDesktop' --exclude='.AppleDouble' --exclude='.com.apple.timemachine.supported' --exclude='.dbfseventsd' --exclude='.DocumentRevisions-V100*' --exclude='.DS_Store' --exclude='.fseventsd' --exclude='.PKInstallSandboxManager' --exclude='.Spotlight*' --exclude='.SymAV*' --exclude='.symSchedScanLockxz' --exclude='.TemporaryItems' --exclude='.Trash*' --exclude='.vol' --exclude='.VolumeIcon.icns' --exclude='Desktop DB' --exclude='Desktop DF' --exclude='hiberfil.sys' --exclude='lost+found' --exclude='Network Trash Folder' --exclude='pagefile.sys' --exclude='Recycled' --exclude='RECYCLER' --exclude='System Volume Information' --exclude='Temporary Items' --exclude='Thumbs.db' /src/dir/ /dst/dir/
# With exlude list `--exclude-from=exclude-list.txt`:cat>exclude-list.txt<<'EOF'# https://alexkaloostian.com/2015/01/22/what-are-all-these-hidden-items-on-my-mac-part-1/# http://superuser.com/questions/180582/what-are-desktop-db-or-desktop-df-files-on-external-hd# http://forum.mac4ever.com/pourquoi-t73534.html#p997828# http://netatalk.sourceforge.net/wiki/index.php/Special_Files_and_Folders# Apple OS.AppleDouble.com.apple.timemachine.donotpresent.com.apple.timemachine.supported.Spotlight-V100.DocumentRevisions-V100.DS_Store.Trash.Trashes.VolumeIcon.icns._.Trashes.fseventsd.dbfseventsd.metadata_never_index.LSOverride.MobileBackups.TemporaryItems.file.hotfiles.btree.quota.ops.user.quota.user.quota.ops.group.quota.group.vol.PKInstallSandboxManager.PKInstallSandboxManager-SystemSoftware# Max OS6-9Desktop DBDesktop DF# AFP.AppleDB.AppleDesktopTemporary ItemsNetwork Trash Folder.apdisk# Sherlock files Mac OS 8.5 to OSX 10.3TheFindByContentFolderTheVolumeSettingsFolder.FBCIndex.FBCSemaphoreFile.FBCLockFolder# http://apple.stackexchange.com/questions/14980/why-are-dot-underscore-files-created-and-how-can-i-avoid-them# https://en.wikipedia.org/wiki/AppleSingle_and_AppleDouble_formats# See also dot_clean command#._*# Linuxlost+found# Windows$RECYCLE.BIN$Recycle.BinThumbs.dbehthumbs.dbehthumbs_vista.dbpagefile.syshiberfil.sysdesktop.iniRecycledRECYCLERSystem Volume Information# Other.SymAV*.symSchedScanLockxz# Package manager cachenode_modulesEOF
# Quick math (Calculate φ). See also bcecho'(1 + sqrt(5))/2'|bc-l# Calculate π the unix wayseq-f'4/%g'1299999|paste-sd-+|bc-l# More complex (int) e.g. This shows max FastE packet rateecho'pad=20; min=64; (100*10^6)/((pad+min)*8)'|bc# Python handles scientific notationecho'pad=20; min=64; print (100E6)/((pad+min)*8)'|python# Plot FastE packet rate vs packet sizeecho'pad=20; plot [64:1518] (100*10**6)/((pad+x)*8)'|gnuplot-persist# Base conversion (decimal to hexadecimal)echo'obase=16; ibase=10; 64206'|bc# Base conversion (hex to dec) ((shell arithmetic expansion))echo $((0x2dec))# Unit conversion (metric to imperial)units-t'100m/9.58s''miles/hour'# Unit conversion (SI to IEC prefixes)units-t'500GB''GiB'# Definition lookupunits-t'1 googol'# Add a column of numbers. See also add and funcpyseq100| (tr'\n'+; echo0) |bc
Date and clock
# Display a calendarcal-3# Display a calendar for a particular month yearcal91752# System datedate# Set system date and time `MonthDayhoursMinutesYear.Seconds`date041217002020.00# save date changes on BIOSclock-w# What date is it this friday. See also daydate-dfri# Exit a script unless it's the last day of the month[ $(date-d'12:00 +1 day'+%d) ='01' ] ||exit# What day does xmas fall on, this yeardate--date='25 Dec'+%A# Convert seconds since the epoch (1970-01-01 UTC) to datedate--date='@2147483647'# What time is it on west coast of US (use tzselect to find TZ)TZ='America/Los_Angeles'date# What's the local time for 9AM next Friday on west coast USdate--date='TZ="America/Los_Angeles" 09:00 next Fri'
Locale
# Print number with thousands grouping appropriate to localeprintf"%'d\n"1234# Use locale thousands grouping in ls. See also lBLOCK_SIZE=\'1ls-l# Extract info from locale databaseecho"I live in $(localeterritory)"# Lookup locale info for specific country. See also ccodesLANG=en_IE.utf8localeint_prefix# List fields available in locale databaselocale-kc $(locale|sed-n's/\(LC_.\{4,\}\)=.*/\1/p') |less
Packages
RPM Packages ( Fedora, Red Hat and like):
# install a rpm packagerpm-ivh [package.rpm]# install a rpm package ignoring dependencies requestsrpm-ivh--nodeeps [package.rpm]# upgrade a rpm package without changing configuration filesrpm-U [package.rpm]# upgrade a rpm package only if it is already installedrpm-F [package.rpm]# remove a rpm packagerpm-e [package]# show all rpm packages installed on the systemrpm-qa# show all rpm packages with the name "httpd"rpm-qa|grephttpd# obtain information on a specific package installedrpm-qi [package]# show rpm packages of a group softwarerpm-qg"System Environment/Daemons"# show list of files provided by a rpm package installedrpm-ql [package]# show list of configuration files provided by a rpm package installedrpm-qc [package]# show list of dependencies required for a rpm packetrpm-q [package] --whatrequires# show capability provided by a rpm packagerpm-q [package] --whatprovides# show scripts started during installation / removalrpm-q [package] --scripts# show history of revisions of a rpm packagerpm-q [package] --changelog# verify which rpm package belongs to a given filerpm-qf/etc/httpd/conf/httpd.conf# show list of files provided by a rpm package not yet installedrpm-qp [package.rpm] -l# import public-key digital signaturerpm--import/media/cdrom/RPM-GPG-KEY# verify the integrity of a rpm packagerpm--checksig [package.rpm]# verify integrity of all rpm packages installedrpm-qagpg-pubkey# check file size, permissions, type, owner, group, MD5 checksum and last modificationrpm-V [package]# check all rpm packages installed on the system - use with cautionrpm-Va# verify a rpm package not yet installedrpm-Vp [package.rpm]-`rpm-ivh/usr/src/redhat/RPMS/`arch`/[package.rpm]`:installapackagebuiltfromarpmsource# extract executable file from a rpm packagerpm2cpio [package.rpm] |cpio--extract--make-directories*bin*# build a rpm package from a rpm sourcerpmbuild--rebuild [package.src.rpm]# List all packages by installed size (Bytes) on rpm distrosrpm-q-a--qf'%10{SIZE}\t%{NAME}\n'|sort-k1,1n
YUM packages tool (Fedora, RedHat and alike):
# download and install a rpm packageyum-yinstall [package]# That will install an RPM, and try to resolve all the dependencies for you using your repositories.yumlocalinstall [package.rpm]# update all rpm packages installed on the systemyum-yupdate# upgrade a rpm packageyumupdate [package]# remove a rpm packageyumremove [package]# list all packages installed on the systemyumlist# find a package on rpm repositoryyumsearch [package]# clean up rpm cache erasing downloaded packagesyumclean [package]# remove all files headers that the system uses to resolve dependencyyumcleanheaders# remove from the cache packages and headers filesyumcleanall
DEB packages (Debian, Ubuntu and like):
# install / upgrade a deb packagedpkg-i [package.deb]# remove a deb package from the systemdpkg-r [package]# show all deb packages installed on the systemdpkg-l# show all deb packages with the name "httpd"dpkg-l|grephttpd# obtain information on a specific package installed on systemdpkg-s [package]# show list of files provided by a package installed on systemdpkg-L [package]# show list of files provided by a package not yet installeddpkg--contents [package.deb]# verify which package belongs to a given filedpkg-S/bin/ping# List all packages by installed size (KBytes) on deb distrosdpkg-query-W-f='${Installed-Size;10}\t${Package}\n'|sort-k1,1n
APT packages tool (Debian, Ubuntu and alike):
# returns list of packages which corresponds string "searched-packages"apt-cachesearch [package]# install / upgrade a deb package from cdromapt-cdrominstall [package]# install / upgrade a deb packageapt-getinstall [package]# update the package listapt-getupdate# upgrade all of the installed packagesapt-getupgrade# remove a deb package from systemapt-getremove [package]# verify correct resolution of dependenciesapt-getcheck# clean up cache from packages downloadedapt-getclean
Pacman packages tool (Arch, Frugalware and alike):
# Install package `name` with dependenciespacman-Sname# Delete package `name` and all files of itpacman-Rname
Monitoring and debugging
fuserlsofls-l/proc/[processid]/fdls-l/proc/*/fdfor p in[0-9]*; dols-l/proc/$p/fd ;donestracelssomeexe>/dev/null&sudodtruss-f-topen-p $!inotifywait-m-r-eOPEN/path/to/traced/directory# Displays status of RAM in megabytesfree-m# Force closure of the process and finish itkill-9process_id# force a process to reload configurationkill-1process_id# Show history rebootlastreboot# Display kernel loadedlsmod# Display a list of files opened by processeslsof-pprocess_id# Displays a list of open files in a given path systemlsof/home/user1# Displays linux tasksps-eafw# Displays linux tasks in a hierarchical modeps-e-opid,args--forest# Shows a tree system processespstree# Monitoring reliability of a hard-disk through SMARTsmartctl-A/dev/hda# Check if SMART is active on a hard-disksmartctl-i/dev/hda# Display system calls made and received by a processstrace-cls>/dev/null# Display library callsstrace-f-eopenls>/dev/null# Show events inherent to the process of booting kerneltail/var/log/dmesg# Show system eventstail/var/log/messages# Display linux tasks using most cputop# Display interrupts in real-timewatch-n1'cat /proc/interrupts'# Show shared libraries required by ssh programldd/usr/bin/ssh# See alsoauditctlinotify
# Get process details for process ID 3117/proc/3117# Monitor messages in a log filetail-f/var/log/messages# Summarise/profile system calls made by commandstrace-cls>/dev/null# Show file opensechoexit|stracebash-li|&grep'^open'# List system calls made by commandstrace-f-eopenls>/dev/null# Monitor what's written to stdout and stderrstrace-f-etrace=write-ewrite=1,2ls>/dev/null# List library calls made by commandltrace-f-egetenvls>/dev/null# List opened files and ports# http://en.wikipedia.org/wiki/Lsoflsof# List paths that process id has openlsof-p $$# List processes that have specified path openlsof~# Show network traffic except ssh. See also tcpdump_not_metcpdumpnotport22# List processes in a hierarchyps-e-opid,args--forest# List processes by % cpu usageps-e-opcpu,cpu,nice,state,cputime,args--sortpcpu|sed'/^ 0.0 /d'# List processes by mem (KB) usage. See also ps_mem.pyps-e-orss=,args=|sort-b-k1,1n|pr-TW$COLUMNS# List all threads for a particular processps-Cfirefox-bin-L-opid,tid,pcpu,state# List elapsed wall time for particular process IDsps-p1,$$ -oetime=# Show system reboot historylastreboot# Show amount of (remaining) RAM (-m displays in MB)free-m# Watch changeable data continuouslywatch-n.1'cat /proc/interrupts'# Monitor udev events to help configure rulesudevadmmonitor# Active processesps-A# Active processes - Tree processes/bin/psacxfwwwe# Active processes - Live displaytop# List active network connections (TCP) with corresponding processesnetstat-ape
System
System information
See also sysinfo.
# Show name and version of distributionhead-n1/etc/issue# Show kernel version and system architectureuname-a# show architecture of machine(2)uname-m# show used kernel versionuname-r# show architecture of machinearch# show information CPU infocat/proc/cpuinfo# show interruptscat/proc/interrupts# verify memory usecat/proc/meminfo# show file(s) swapcat/proc/swaps# show version of the kernelcat/proc/version# show network adpters and statisticscat/proc/net/dev# show mounted file system(s)cat/proc/mounts# Show RAM total seen by the systemgrepMemTotal/proc/meminfo# Show CPU(s) infogrep"model name"/proc/cpuinfo# Show PCI infolspci-tv# Show USB infolsusb-tv# Show state of cells in laptop batterygrep-Fcapacity:/proc/acpi/battery/BAT0/info# Display SMBIOS/DMI informationdmidecode-q|less
Power management
Aka shutdown, restart and logout of a system
# shutdown system(2)init0# leaving sessionlogout# reboot(2)reboot# shutdown system(1)shutdown-hnow# planned shutdown of the system at 16:30shutdown-h16:30&# cancel a planned shutdown of the systemshutdown-c# rebootshutdown-rnow# shutdown systemtelinit0
Interactive
See also linux keyboard shortcuts
# Line editor used by bash, python, bc, gnuplot, ...readline# Virtual terminals with detach capability, ...screen# Visual file manager that can browse rpm, tar, ftp, ssh, ...mc# Interactive/scriptable graphinggnuplot# Web browserlinks# open a file or url with the registered desktop applicationxdg-open.
Shell
Command-line interface (CLI), not for graphical user interface (GUI)
# Display current shell prompt settingecho $PS1# Change current shell prompt settingexport PS1="..."export PS1="\[\033[0m\]\[\033[0;30;47m\] \u\[\033[0m\]\[\033[0;30;47m\]@\h\[\033[0m\] \w\n\[\033[1;32m\] \@ \$ \[\033[0m\]"export PS1="[${LOGNAME}@$(hostname)]"
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 to if [ -s ~/.bashrc ]; then source ~/.bashrc; fi in ~/.profile for that case)
(user) ~/.bash_logout au logout
(and /etc/bash.bashrc, /etc/bash.bashrc.local?)
To reload a configuration file (here the file ~/.bashrc)
source~/.bashrc# or use dot command:.~/.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
# History auto complete with "start with" filter"\e[5~":history-search-backward"\e[6~":history-search-forwardsetshow-all-if-ambiguousonsetcompletion-ignore-caseon
# Relative to execution path:#source /path/to/script.sh# So use this instead:source $(dirname $0)/script.sh# Or:CURRENT_DIR=`dirname $0`$CURRENT_DIR/script.sh
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:
command$'\t'
Wildcard files:
for file in*.ext1; doecho"${file} ${file/.ext1/.ext2}"; done
echo"The current user (\$USER) \"$USER\" use the shell (\$SHELL) \"$SHELL\""echo'The current user ($USER) "'"$USER"'" use the shell ($SHELL) "'"$SHELL"'"'
Shell parameter expansion:
# Remove trailing slash for all arguments `a/ b/c/ d /` output `a b/c d`echo ${@%/}# myvar=a/b/// output `a/b`shoptextglobecho ${myvar%%+(/)}somevar=$(echo"$value"|sed's:/*$::')echo $somebardir=/a/b///echo $(realpath-s--canonicalize-missing $dir)# Construct command parts as an arraymycommand=(/some/command"$PATH_NAME")# Print the commandprintf'%s\n'"${mycommand[*]}"# Execute command"${mycommand[@]}"
cat>/path/to/file<<EOFSome thing.Blahblah!$somevarEOFcat>/path/to/file<<<"Some thing."cat<<EOFtest1test2EOF(cat<<'EOF'file1file2EOF) |whileread-rfile; docp"from/$file""to/$file";done;cat<<EOF>>greetings.txtline 1line 2EOF# Here-doc to var# Use `IFS=` otherwise any leading and trailing spaces will be trimmed# Use `<<'EOF'` instead `<<EOF` to ignore variables tokensIFS=read-r-d''MYVAR<<'EOF'abc'asdf"$(dont-execute-this)foo"bar"''EOF
# Empty a file (ex: clean a log file)> /var/log/apache2/error.log# Append to a fileecho"Appended text">>/path/file# Log all infos (and erros) of following commands to a file `/tmp/log.txt`( /bin/psacxfwwwe2>&1; /usr/sbin/lsof-Pwln2>&1; /bin/netstat-anpe2>&1; /usr/bin/lastlog2>&1; /usr/bin/last2>&1; /usr/bin/who-a2>&1 ) >/tmp/log.txt
# Enter to directory `/home`cd/home# Go back one levelcd..# Go back two levelscd../..# Go to $HOME directorycd# Go to home directorycd~user1# Go to previous directorycd-# Get the current working directorypwd# Go to dir, execute command and return to current dir(cddir&&command)# Put current dir on stack so you can popd back to itpushd .
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:
# Modify timestamp of a file or directory - (YYMMDDhhmm)touch-t0712250000file1# Create directories `dir1` and `dir2` (in same parent dir)mkdirdir1dir2# Try to create a directory treemkdir-p/tmp/dir1/subdir1# Extract music from m3u (ignore lines start with #, whitespace or are empty)# Playlists entries could be relativecd"/path/to/playlists"cat"playlist1.m3u""playlist1.m3u""playlist3.m3u"|grep"^[^# \t]"|tr-s'\n'|whileread-rline; docp--parent-v"$line"/destination; done# Get extensions of all filesfind.-typef-printf"%f\n"|grep-o-E'(\.[^\.]*)$'|sort|uniq# File checksum SHA256, used in chef cookbooksopenssldgst-sha256path/to/myfile# File checksumMD5openssldgst-md5path/to/myfile# Read or write BSD-style checksum file# https://unix.stackexchange.com/a/476480/60668sha256sum-cSHA256SUMSpath/to/myfilesha256sum--tagpath/to/myfile# Encrypt a file with GNU Privacy Guardgpg-cfile1# Decrypt a file with GNU Privacy Guardgpgfile1.gpg# Create hardlink aka hardware link# Note: It's not possible to create hardlink with a directory (due to the risk of loops in tree)ln/path/to/source_file/path/to/target_fileln-T/etc/apache2/sites-available/example.com/etc/apache2/sites-enabled/example.com# Remove file linkunlink/etc/apache2/sites-enabled/websiteA.exemple# Create a symbolic link to file or directoryln-sfile1lnk1
File listing and searching
Find support shell pattern for -path and -ipath parameters:
# Find all files that have been modified in the past 7 daysfind.-typef-mtime-7# Search binary files are not used in the last 100 daysfind/usr/bin-typef-atime+100# Find all JPEGs that have been modified more than 30 days agofind.-name \*.jpg-mtime+30# Move all JPEGs from the current folder (recursively) that are greater than 40k into the folder /tmp/2find.-name \*.jpg-size+40k-execmv{}/tmp/2+# search files and directories belonging to `user1`find/-useruser1# List files by date. See also newest and find_mm_yyyyls-lrt# Print in 9 columns to width of terminalls/usr/bin|pr-T9-W$COLUMNS# Search 'expr' in this dir and below. See also findrepofind-name'*.[ch]'|xargsgrep-E'expr'# Search all regular files for 'example' in this dir and belowfind-typef-print0|xargs-r0grep-F'example'# Search all regular files for 'example' in this dirfind-maxdepth1-typef|xargsgrep-F'example'# Process each item with multiple commands (in while loop)find-maxdepth1-typed|whilereaddir; doecho $dir; echocmd2; done# Get filename (without the extension)find./-name"tile_*.png"-execbash-c'filename="$1";echo "${filename%.*}"'_{} \;# search files with `.bin` extension within directory `/home/user1`find/home/user1-name \*.bin# Search files with `.rpm` extension and modify permitsfind/-name*.rpm-execchmod755'{}' \;# Search files with `.rpm` extension ignoring removable partitions as cdrom, pen-drive, etc.…find/-xdev-name \*.rpm# Find files with the `.ps` extension - first run `updatedb` commandlocate \*.ps#Search cached index for names. This re is like glob *file*.txtlocate-r'file[^/]*\.txt'# Find files not readable by all (useful for web site)find-typef!-perm-444# Find dirs not accessible by all (useful for web site)find-typed!-perm-111# Search for empty files and folder (or file with only whitespaces)find-empty# List all folders and files, ordered by sizedu-ak.|sort-nr|less# List top 10 largest files and directoriesdu-a/var|sort-n-r|head-n10# Quickly search (sorted) dictionary for prefixlookreference# Append to each filesfind-typef-execsh-c'echo "something" >> "$1"'_{} \;find-typef-print0|while IFS=read-r-d''file; doecho"something">>"$file"; donefind-typef-execbash-c'for file; do echo "something" >> "$file"; done'_{} \+# See also https://serverfault.com/questions/343705/how-do-i-append-a-specific-number-of-null-bytes-to-a-file/
# Use a simple shell loop, to process each of the images.mkdirthumbnailsfor f in*.jpgdoconvert $f -thumbnail200x90thumbnails/$f.gifdone# Use find to substitute filenames into a 'convert' command.# This also provides the ability to recurse though directories by removing# the -prune option, as well as doing other file checks (like image type,# or the disk space used by an image).find*-prune-name'*.jpg' \-execconvert'{}'-thumbnail200x90thumbnails/'{}'.gif \;# Use xargs -- with a shell wrapper to put the argument into a variable# This can be combined with either "find" or "ls" to list filenames.ls*.jpg|xargs-n1sh-c'convert $0 -thumbnail 200x90 thumbnails/$0.gif'# An alternative method on Linux (rather than plain Unix)# This does not need a shell to handle the argument.ls*.jpg|xargs-r-IFILEconvertFILE-thumbnail200x90FILE_thumb.gif
# Find multiple exec a executed only if the previous one exit with 0 https://stackoverflow.com/questions/5119946/find-exec-with-multiple-commands#comment34296391_6043896find-typef-iname"*.properties"-execgrep-q-i-E'^abtest=false$'{} \; -printfind-typef-iname"*.properties"-execgrep-q-i-E'^abtest='{} \; -execsed-i's/^abtest=.*/abtest=true/i'{} \; -print# Use test to inverse the grep exit value https://stackoverflow.com/a/30495279/470117 (-v/--invert-match option is not useful for that case), for that we need also sh interpreter to use builtin test command# For append mode (redirection), need to use sh interpreter directly, else {} will be interpreted directly by Bash. See https://superuser.com/questions/1327969/appending-new-lines-to-multiple-files/1327980#1327980# -exec sh -c 'echo "command name: $0, first arg: $1"' test {} \;find-iname"*.properties"-execsh-c'grep -q -i -E "^abtest=" $1; test $? -eq 1'match{} \; -execsh-c'echo -e "\n\nabtest=true" >> $1'append{} \; -printfind-iname"*.properties"-typef-print0|xargs-0grep-EHi'^abtest='# Same as (flexibity of find vs glob include/exclude filters):grep-EHir--include="*.properties"'^abtest='/path/to/dirgrep-ir--include=\*.{php,js,css}"/api/v1/"# Example search in all .less files that contains `url("<url>")` or `url('<url>')` or `url(<url>)`find"$wd"-iname"*.less" \( -not-ipath"*/node_modules/*" \) -typef-print0|xargs-0grep-EliZ'url\(('"'"'|"|)(.*?)\1\)'|xargs-0-n1echo"Do something with that file:"
# Remove `file1` and `file2`rm-ffile1file2# Remove `dir1` and `dir2` and their contents recursivelyrm-rfdir1dir2# Remove directory `dir1`rmdirdir1# Remove all files start with "title_" and ends with ".png"find.-name'tile_*.png'-delete# Remove all files with exceptions:find.-typef-not \( -name'*.php'-or-name'*.iso' \) -execrm{} \;# Remove all files with a list of exceptions:find.-typef-printf"%P\n"!-name"list.txt"|fgrep-vflist.txt|xargs-rrm# Remove empty dirfind<path>-typed-empty-delete# Can also use (not recommanded)find<path>-typed-empty-print0|xargs-0-I{} rmdir "{}"find<path>-typed-print0|xargs-0-rrmdir-p--ignore-fail-on-non-empty# Handle trailing dot rmdir error: rmdir -p "./test" -> rmdir: failed to remove directory '.': Invalid argumentfind-mindepth1-typed-printf'%P\0'|xargs-0-rrmdir-p--ignore-fail-on-non-empty# Find all dirs in reverse order (depth first), remove empty dir to topfind-mindepth1-typed-print0|tac-s$'\0'|xargs-0-rrmdir--ignore-fail-on-non-empty# Delete all Unix hidden files# All files or folders that start with `.`, like `.htaccess` or `.DS_STORE`rm-rf.[^.]*# All dir `.git`find.-name".git"-typed-prune-execrm-rf{}+# All dir `node_modules` (which can recusively contains `node_modules` dirs; Use `-prune` for that)find.-name"node_modules"-typed-prune-execrm-rf{}+
# Rename (move) a file or directorymvdir1new_dir# Change file extensionfor j in/path/dir/*.htmldo n=${j/.html}mv"$j""$n.php"done# Change file extensionfor f in*; domv"$f""$f.bin"; done;# Rename `Ref_00001.jpg` to `anim001.jpg`find.-name'Ref_00*.jpg'-print0|awk'BEGIN {RS = "\0"; ORS = "\0"} {print; gsub(/\/Ref_00/,"/anim"); print }'|xargs-0-n2mv# Or use bash+sed directly, but less performantfor i in'Ref_00'*.jpg; domv"$i""$(echo $i |sed 's/^Ref_00/anim/')"; done;# To test, replace find by: `echo -en "Ref_00001.jpg\0Ref_00002.jpg\0Ref_00002.jpg"` and replace xargs with `xargs -0 -n2 echo`# Rename `sprite1.png` to `sprite0.png`, `sprite2.png` to `sprite1.png`, etc.find.-maxdepth1-typef-execmv"{}""{}.tmp" \; -print0|awk'BEGIN {RS = "\0"; ORS = "\0"} {match($0,/^(.*sprite)([0-9]+)(.*)$/,a); print a[1]a[2]a[3]".tmp"; print a[1]a[2]-1a[3] }'|xargs-0-n2mv# To test, replace find by: `echo -en "sprite1.png\0sprite2.png\0sprite3.png"` and replace xargs with `xargs -0 -n2 echo`# Use Perl rename (util-linux rename.ul, perl prename, p5-file-rename)# Rename *.JPG to *.jpgrename's/\.JPG/\.jpg/'*.JPG# Strip spacesrename's/ //'*.jpg# Lower caserename'y/A-Z/a-z/'*# Copying a filecpfile1file2# Copy all files in dir1 to dir2 (recursively)cp-Rdir1/.dir2/# Copy all files of a directory within the current work directorycpdir/*.# Copy a directory within the current work directorycp-a/tmp/dir1.# Copy a directorycp-adir1dir2# Find and copy all files with `.txt` extension from a directory to anotherfind/home/user1-name'*.txt'|xargscp-av--target-directory=/home/backup/--parents# local copy preserving permissions and links from a directory to anothertarcf-.| (cd/tmp/backup ; tarxf- )
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
# Decompress a file called `file1.bz2`bunzip2file1.bz2# Compress a file called `file1`bzip2file1# Decompress a file called `file1.gz`gunzipfile1.gz# Compress a file called `file1`gzipfile1# Compress with maximum compressiongzip-9file1# Create an archive rar called `file1.rar`rarafile1.rartest_file# Compress `file1`, `file2` and `dir1` simultaneouslyrarafile1.rarfile1file2dir1# Decompress rar archiverarxfile1.rar# Create a uncompressed tarballtar-cvfarchive.tarfile1# Create an archive containing `file1`, `file2` and `dir1`tar-cvfarchive.tarfile1file2dir1# Show contents of an archivetar-tfarchive.tar# Extract a tarballtar-xvfarchive.tar# Extract a tarball into / tmptar-xvfarchive.tar-C/tmp# Create a tarball compressed into bzip2tar-cvfjarchive.tar.bz2dir1# Create a tarball compressed into gziptar-cvfzarchive.tar.gzdir1# Decompress a compressed tar archive in bzip2tar-xvfjarchive.tar.bz2# Decompress a compressed tar archive in gziptar-xvfzarchive.tar.gz# Make a incremental backup of directory `/home/user`tar-Pufbackup.tar/home/user# Decompress rar archiveunrarxfile1.rar# Decompress a zip archiveunzipfile1.zip# Create an archive compressed in zipzipfile1.zipfile1# Compress in zip several files and directories simultaneouslyzip-rfile1.zipfile1file2dir1
Create archive from file list:
#!/bin/bash# Create temp listlist=$(mktemp"/tmp/archive_list.XXXXXXXXXX")# Write stdin file / folder listcat>"$list"# Get destination folder based on first file / folderfirst=$(head-n1"$list")folder=$(dirname"$first")# Temporary file and final filefinal="$folder/Archive.zip"file="$final.tmp"# Create archive file (zip, ultra)/opt/local/bin/7za-tzip-mx=9"$file"@"$list"# Move to final destinationmv"$file""$final"# Remove temp listrm"$list"
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
source=dirA/file.extdest_dir=dirBfile=$(basenamefile.ext)basename=${file%.*}ext=${file##*.}if [[ !-e"$dest_dir/$basename.$ext" ]]; then# file does not exist in the destination directorymv"$source""$dest_dir"else num=2while [[ -e"$dest_dir/$basename-$num.$ext" ]]; do (( num++ ))donemv"$source""$dest_dir/$basename-$num.$ext"fi
File attributes
# Allows write opening of a file only append modechattr+afile1# Allows that a file is compressed / decompressed automatically by the kernelchattr+cfile1# Makes it an immutable file, which can not be removed, altered, renamed or linkedchattr+ifile1# All attributes (see details in the manpage of `chattr`):# - append only (a)# - compressed (c)# - no dump (d)# - extent format (e)# - immutable (i)# - data journalling (j)# - secure deletion (s)# - no tail-merging (t)# - undeletable (u)# - no atime updates (A)# - synchronous directory updates (D)# - synchronous updates (S)# - top of directory hierarchy (T)# show specials attributeslsattr
File type
# Get file type if known by libmagicfile--mime/path/file# Get information about files in the current folderfind.-maxdepth1-typef-execfile"{}" \;
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
# Test if a file existfilename=$1if [ -f $filename ]thenecho"$filename exists"elseecho"$filename does NOT exist"fi
Files permissions
# Change group of fileschgrpgroup1file1# Set permissions reading (r), write (w) and (x) access to users owner (u) group (g) and others (o)chmodugo+rwxdirectory1# Remove permits reading (r), write (w) and (x) access to users group (g) and others (orchmodgo-rwxdirectory1# Set SUID bit on a binary file - the user that running that file gets same privileges as ownerchmodu+s/bin/file1# Disable SUID bit on a binary filechmodu-s/bin/file1# Set SGID bit on a directory - similar to SUID but for directorychmodg+s/home/public# Disable SGID bit on a directorychmodg-s/home/public# Set STIKY bit on a directory - allows files deletion only to legitimate ownerschmodo+t/home/public# Disable STIKY bit on a directorychmodo-t/home/public# Change owner of a filechownuser1file1# Change user owner of a directory and all the files and directories contained insidechown-Ruser1directory1# Change user and group ownership of a filechownuser1:group1file1# View all files on the system with SUID configuredfind/-perm-u+s
Name, extension and parent folder
Note: Don't use parameter substitution, it's not work with all cases
# View the contents of a file starting from the first rowcatfile1# View first two lines of a filehead-2file1# Pagers (moving down the file content one screen at a time)# View content of a file along, allowing only forward navigation through the filemorefile1# View content of a file along, allowing forward and backward navigation through the filelessfile1# View the contents of a file starting from the last linetacfile1# View last two lines of a filetail-2file1# View in real time what is added to a filetail-f/var/log/messages# View from line 20 to 30 of a filesed-n'20,30 p'file1# View from line 20 to end of a filesed-n'20,$ p'file1# View from the begining to line 20 of a filesed-n'1,20 p'file1# Divide into 5 columnsls/tmp|pr-T5-W$COLUMNS
# Create or tuncate a file> /var/log/apache2/error.log# Create an empty file or change the modification datetouchfile.ext# Create a large test file (taking no space)ddbs=1seek=2TBif=/dev/nullof=file.ext
File comparaisons
Note: you can export LANG=C for speed. Also these assume no duplicate lines within a file
# Union of unsorted filessortfile1file2|uniq# Intersection of unsorted filessortfile1file2|uniq-d# Difference of unsorted filessortfile1file1file2|uniq-u# Symmetric Difference of unsorted filessortfile1file2|uniq-u# Union of sorted filesjoin-t'\0'-a1-a2file1file2# Intersection of sorted filesjoin-t'\0'file1file2# Difference of sorted filesjoin-t'\0'-v2file1file2# Symmetric Difference of sorted filesjoin-t'\0'-v1-v2file1file2
Use diff and patch
Compare 2 folders:
Sans -q mais avec -u pour faire un patch
diff-rq/path/dirA/path/dirB
Et sans prendre en compte les fichiers metadonnées d'OSX et de Windows, le tout ordonné :
Aka folder link, like symlink but for folder (standart implementation don't allow to link folder)
# Mount a folder at a specific point (here `/path/destdir`)mount--bind/path/srcdir/path/destdir# Unmountumount/path/destdir
The mount point is registerd in /etc/fstab as fs-type: bind
Archives and compression
# Encrypt filegpg-cfile# Decrypt filegpgfile.gpg# Make compressed archive of dir/tar-cdir/|bzip2>dir.tar.bz2# Find all files with `.log` extension and make an bzip archivefind/var/log-name'*.log'|tarcv--files-from=-|bzip2>log.tar.bz2# Extract archive (use gzip instead of bzip2 for tar.gz files)bzip2-dcdir.tar.bz2|tar-x# Make encrypted archive of dir/ on remote machinetar-cdir/|gzip|gpg-c|sshuser@remote'dd of=dir.tar.gz.gpg'# Make archive of subset of dir/ and belowfinddir/-name'*.txt'|tar-c--files-from=-|bzip2>dir_txt.tar.bz2# Make copy of subset of dir/ and belowfinddir/-name'*.txt'|xargscp-a--target-directory=dir_txt/--parents# Copy (with permissions) copy/ dir to /where/to/ dir( tar-c/dir/to/copy ) | ( cd/where/to/&&tar-x-p )# Copy (with permissions) contents of copy/ dir to /where/to/( cd/dir/to/copy&&tar-c. ) | ( cd/where/to/&&tar-x-p )# Copy (with permissions) copy/ dir to remote:/where/to/ dir( tar-c/dir/to/copy ) |ssh-Cuser@remote'cd /where/to/ && tar -x -p'# Backup harddrive (raw) to remote machineddbs=1Mif=/dev/sda|gzip|sshuser@remote'dd of=sda.gz'
Incremental listing
Incrementaly add/changed/delete files (list made from cron or similar)
Use recode that obsoletes iconv, dos2unix, unix2dos
# Show available conversions (aliases on each line)recode-l#iconv -l# Windows "ansi" to local charset (auto does CRLF conversion)recodewindows-1252..file_to_change.txt# Windows utf8 to local charsetrecodeutf-8/CRLF..file_to_change.txt# Latin9 (western europe) to utf8recodeiso-8859-15..utf8file_to_change.txt#iconv -f iso-8859-15 -t utf-8 <infile> -o <outfile># Base64 encode / decoderecode../b64<file.png# Quoted printable decoderecode/qp..<file.qp>file.txt# Text to HTMLrecode..HTML<file.txt>file.html# Lookup table of charactersrecode-lfwindows-1252|grepeuro# Convert a text file format from MSDOS to UNIX (line-ending CRLF to LF)recodeibmpc..latin1filefile2#dos2unix file file2#cat file | tr -d '\r' > file2 && mv -v file2 file#sed -i s/\r//g file# convert a text file format from UNIX to MSDOS (line-ending LF to CRLF)recodelatin1..ibmpcfilefile2#unix2dos file file2#sed -i 's/$/\r/' file# Show what a code represents in latin-9 charmapecho-n0x80|recodelatin-9/x1..dump# Show latin-9 encodingecho-n0x20AC|recodeucs-2/x2..latin-9/x# Show utf-8 encodingecho-n0x20AC|recodeucs-2/x2..utf-8/x
Temporary file
temp_file=$(mktemp)# Remove the file when the script exittrap"rm -f $temp_file"0# do something with the fileecho"Hello World!"> $temp_filecat $temp_file# Remove the file now (optional)rm-f"$temp_file"# Do something else
If sed pattern come from variable, some escaping is needed: sed "s/$BRE/$REPL/"
Instead use awk with variables:
prefix=/some/path/to/# awk sub() can be use to replace with regexfind-printf'%P\0'|awk-vprefix="$prefix"'BEGIN {RS = "\0"; ORS = "\0"} {print prefix $0}'|do_something_with_null_sep_list
contents="$(jq '.address = "abcde"' test.json)"&&echo-E"${contents}">test.json# Note "contents" cannot contain a literal null character. Bash variables cannot store literal nulls.
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.
functionrelative_path_from_to() {# strip trailing slashes path1=${1%\/} path2=${2%\/}# common part of both paths common=$(printf'%s\x0%s'"${path1}""${path2}"|sed's/\(.*\/\).*\x0\1.*/\1/')# how many directories we have to go up to the common part up=$(grep-o"/"<<<${path1#$common}|wc-l)# create a prefix in the form of ../../ ... prefix=""; for ((i=0; i<=$up; i++)); do prefix="$prefix../"; done# return prefix plus second path without commonprintf"$prefix${2#$common}"}relative_path_from_to/path/test1/file/path/test2/file# > ../../test2/file
# require the path of both file and dir to exist, resolve symlinkrealpath--relative-to=DIRFILE
# Echo multiline string (use the newline separator `\n`)echo-e"a\nb"# Add line to begin of file, aka prepend textecho"firstline"|cat-file.txt>file.txt.tmp&&mvfile.txt.tmpfile.txt# Convert from lower case in upper casetr'[:lower:]''[:upper:]'# Sort contents of two filessortfile1file2# Sort contents of two files omitting lines repeatedsortfile1file2|uniq# Sort contents of two files by viewing only unique linesortfile1file2|uniq-u# Sort contents of two files by viewing only duplicate linesortfile1file2|uniq-d# Sort IPV4 ip addressessort-t.-k1,1n-k2,2n-k3,3n-k4,4n# Filter non printable characterstr-dc'[:print:]'# cut fields separated by blankstr-s'[:blank:]''\t'# Count lineswc-l# Number row of a filecat-nfile1# Compare contents of two files by deleting only unique lines from `file1`comm-1file1file2# Compare contents of two files by deleting only unique lines from `file2`comm-2file1file2# Compare contents of two files by deleting only the lines that appear on both filescomm-3file1file2# Compare with awk: https://stackoverflow.com/questions/15065818/compare-files-with-awk# Find differences between two filesdifffile1file2# Look up words "Aug" on file `/var/log/messages`grepAug/var/log/messages# Look up words that begin with "Aug" on file `/var/log/messages`grep^Aug/var/log/messages# Select from file `/var/log/messages` all lines that contain numbersgrep [0-9] /var/log/messages# Search string "Aug" at directory `/var/log` and belowgrepAug-R/var/log/*# Find text in filesgrep-rn"texttofind"*grep"string text to find in all files".-R# Highlight occurances of regular expression in dictionarygrep--colorreference/usr/share/dict/words# Merging contents of two files for columnspastefile1file2# Merging contents of two files for columns with `+` delimiter on the centerpaste-d'+'file1file2# Find differences between two files and merge interactively alike `diff`sdifffile1file2# Find in files with a multile regex# See https://stackoverflow.com/a/7167115/470117find./path/to/files-typef-execgrep-Pazo'(?s)<control>.*?</control>'{} \+# Split string into an arraymapfile-d''array<<(echo-en "a\0b\0c")# Join array with single char separatorecho"$(IFS=, ; echo "${array[*]}")"# Join array with multi chars separatorprintf"\"%s\",""${array[@]}"
Note: sed uses stdin and stdout. Newer versions support inplace editing with the -i option
Remove multiline comment:
# Remove in place all multiline comments# Note: see also m regex flagsed-Ei-e'1h;2,$H;$!d;g'-e's|/\*.*?\*/||g'file.ext# Single line only (sed match by default on line basis)sed-i'/<!--.*-->/ d'file# Note: the , implied the multiple lines.sed-i'/<!--/,/-->/ d'file
#/bin/bash# Search files that match some pre conditions then apply remplacements# find . -iname "*.aspx" -type f -exec grep -q -i -E "Page Language=\"VB\"" {} \; -exec grep -q -i -E "<Fnac:HtmlFooter" {} \; -exec ./substitute.sh {} \; -exec unix2dos -q {} \; -printREGEXP='<Fnac:HtmlFooter\s+ID="HtmlFooter"\s+runat="server"(\s+Omniture="Default")?\s+OmnitureEVar2="([^"]*)"(\s+OmniturePageName="([^"]*)")?(\s+TagCommander="Default")?\s+TagCommanderIdentifier="1"\s+TagCommanderTemplateType="([^"]*)"\s+TagCommanderTemplateName="([^"]*)"\s+/>'# All chars must be escaped, only newlines are kept for readabilityREPLACEMENT=$(cat<<EOF|sed':a;N;$!ba;s/\n/\\n/g'<%' Html.SetTrackingValues(Tracker.Omniture, new {...});TrackingHelpers.SetTrackingValues(Tracker.TagCommander, New With{ Key .template_type = "\6", Key .template_name = "\7"})TrackingHelpers.SetTrackingValues(Tracker.Omniture, New With{ Key .eVar2 = "\2", Key .pageName = "\4"})%><%=WebFormsMvcUtilities.Partial("~/Shared/_Tracking.cshtml", New List(Of Tracker)({ Tracker.TagCommander, Tracker.Omniture }))%></body></html>EOF)sed-Ei's|<%@ Register TagPrefix="fnac" TagName="HtmlFooter" Src="~/Nav/Core/Common/HtmlControls/HtmlFooter.ascx" %>||'"$@"sed-Ei-e'1h;2,$H;$!d;g'-e"s|$REGEXP|$REPLACEMENT|""$@"
# Replace text in file, need a temp file# Note: if `old-text` contains slashes `/`, back slash them: `../..` give `..\/..`sed"s/old-text/new-text/g"file.txt>file.txt.tmp&&mvfile.txt.tmpfile.txt# Replace string1 with string2sed's/string1/string2/g'# Modify anystring1 to anystring2sed's/\(.*\)1/\12/g'# Remove comments and blank linessed'/^ *#/d; /^ *$/d'# Concatenate lines with trailing \sed':a; /\\$/N; s/\\\n//; ta'# Remove trailing spaces from linessed's/[ \t]*$//'# Escape shell metacharacters active within double quotessed's/\([`"$\]\)/\\\1/g'# Right align numbersseq10|sed"s/^/ /; s/ *\(.\{7,\}\)/\1/"# Duplicate a columnseq10|sedp|paste--# Print 1000th linesed-n'1000{p;q}'# Print lines 10 to 20sed-n'10,20p;20q'# Extract title from HTML web pagesed-n's/.*<title>\(.*\)<\/title>.*/\1/ip;T;q'# Delete a particular linesed-i42d~/.ssh/known_hosts# Replace "string1" with "string2"sed's/string1/string2/g'# Remove all blank linessed'/^$/d'# Remove comments and blank linessed'/ *#/d; /^$/d'# Eliminates the first linesed-e'1d'# View only lines that contain the word `string1`sed-n'/string1/p'# Remove empty characters at the end of each rowsed-e's/ *$//'# Remove only the word "string1" from text and leave intact allsed-e's/string1//g'# Print from 1th to 5th row of example.txtsed-n'1,5p'# Print row number 5 of example.txtsed-n'5p;5q'# Replace more zeros with a single zerosed-e's/00*/0/g'
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.
# Print all fieldsawk'{print NR": "$0; for(i=1;i<=NF;++i) print "\t"i": "$i}'# Remove all even linesawk'NR%2==1'# View the first column of a lineechoabc|awk'{print $1}'# View the first and third column of a lineechoabc|awk'{print $1,$3}'
# Mounting a Filesystem:# force umount when the device is busyfuser-km/mnt/hda2# mount disk called hda2 - verify existence of the directory `/mnt/hda2`mount/dev/hda2/mnt/hda2# mount a floppy diskmount/dev/fd0/mnt/floppy# mount a cdrom / dvdrommount/dev/cdrom/mnt/cdrom# mount a cdrw / dvdrommount/dev/hdc/mnt/cdrecorder# mount a cdrw / dvdrommount/dev/hdb/mnt/cdrecorder# mount a file or iso imagemount-oloopfile.iso/mnt/cdrom# mount a Windows FAT32 file systemmount-tvfat/dev/hda5/mnt/hda5# mount a usb pen-drive or flash-drivemount/dev/sda1/mnt/usbdisk# mount a windows network sharemount-tsmbfs-ousername=user,password=pass//WinClient/share/mnt/share# unmount disk called hda2 - exit from mount point `/mnt/hda2` firstumount/dev/hda2# run umount without writing the file /etc/mtab - useful when the file is read-only or the hard disk is fullumount-n/mnt/hda2# Show all partitions registered on the systemcat/proc/partitions# List mounted filesystems on the system (and align output)mount|column-t# Show info about disk sdahdparm-i/dev/sda# displays the characteristics of a hard-diskhdparm-i/dev/hda# perform test reading on a hard-diskhdparm-tT/dev/sda# Do a read speed test on disk sdahdparm-tT/dev/sda# Test for unreadable blocks on disk sdabadblocks-s/dev/sda# How long has this disk (system) been powered on in totalsmartctl-A/dev/sda|grepPower_On_Hours# Check bad blocks on disk hda1badblocks-v/dev/hda1# Repair / check integrity of dos filesystems on disk hda1dosfsck/dev/hda1# Repair / check integrity of ext2 filesystem on disk hda1e2fsck/dev/hda1# Repair / check integrity of ext3 filesystem on disk hda1e2fsck-j/dev/hda1# Repair / check integrity of linux filesystem on disk hda1fsck/dev/hda1# Repair / check integrity of ext2 filesystem on disk hda1fsck.ext2/dev/hda1# Repair / check integrity of ext3 filesystem on disk hda1fsck.ext3/dev/hda1# Repair / check integrity of fat filesystem on disk hda1fsck.vfat/dev/hda1# Repair / check integrity of dos filesystem on disk hda1fsck.msdos/dev/hda1
Backup the filesystem
# Note: only supported by ext2/ext3 filesystems# Make a full backup of directory `/home`dump-0aj-f/tmp/home0.bak/home# Make a incremental backup of directory `/home`dump-1aj-f/tmp/home0.bak/home# Restoring a backup interactivelyrestore-if/tmp/home0.bak
# Format a floppy diskfdformat-n/dev/fd0# Create a filesystem type linux ext2 on hda1 partitionmke2fs/dev/hda1# Create a filesystem type linux ext3 (journal) on hda1 partitionmke2fs-j/dev/hda1# Create a filesystem type linux on hda1 partitionmkfs/dev/hda1# Create a FAT32 filesystemmkfs-tvfat32-F/dev/hda1
Filesystem swap:
# Create a swap filesystemmkswap/dev/hda3# Activating a new swap partitionswapon/dev/hda3# Activate two swap partitionsswapon/dev/hda2/dev/hdb3
Disk space
See also FSlint
# Show files by size, biggest lastls-lSr|more# Show top disk users in current dir. See also dutopdu-s*|sort-k1,1rn|head# Sort paths by easy to interpret disk usagedu-hs/home/*|sort-k1,1h# Show size of the files and directories sorted by sizedu-sk*|sort-rn# Estimate space used by directory `dir1`du-shdir1# Show free space on mounted filesystems aks disk usagedf-h# Show free inodes on mounted filesystemsdf-i# Show disks partitions sizes and types (run as root)fdisk-l
Clone disk
# Make a copy of a local hard disk on remote host via sshddbs=1Mif=/dev/hda|gzip|sshuser@ip_addr'dd of=hda.gz'# Copy content of the harddrive to a fileddif=/dev/sdaof=/tmp/file1# Make a copy of MBR (Master Boot Record) to floppyddif=/dev/hdaof=/dev/fd0bs=512count=1# Restore MBR from a copy saved to floppyddif=/dev/fd0of=/dev/hdabs=512count=1
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.)
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
# Save copy of data cdromgzip</dev/cdrom>cdrom.iso.gz# Create cdrom image from contents of dirmkisofs-VLABEL-rdir|gzip>cdrom.iso.gz# Mount the cdrom image at /mnt/dir (read only)mount-oloopcdrom.iso/mnt/dir# Clear a CDRWcdrecord-vdev=/dev/cdromblank=fast# Burn cdrom image (use dev=ATAPI -scanbus to confirm dev)gzip-dccdrom.iso.gz|cdrecord-vdev=/dev/cdrom-# Rip audio tracks from CD to wav files in current dircdparanoia-B# Make audio CD from all wavs in current dir (see also cdrdao)cdrecord-vdev=/dev/cdrom-audio-pad*.wav# perform an md5sum on a device, like a CDddif=/dev/hdc|md5sum# mount an ISO imagemount-oloopcd.iso/mnt/iso
Command operations
# Show full path to a binary / executablewhichcommand# Show location of a binary file, source or manwhereiscommand# See how long a command takes (stopwatch). Ctrl-d to stop. See also swtime command# Show commands pertinent to string. See also threadsafe# Display a list of commands that pertain to keywords of a program, useful when you know what your program does, but you don't know the name of the commandapropossomekeyword# Find the location of a commandcommand-vgit2>/dev/null
# displays description of what a program doeswhatissomekeywordmanmv# find any related commandsman-kmv# make a pdf of a manual pageman-tascii|ps2pdf->ascii.pdf
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)
Some commands support also (or instead) an option that show the help, could be:
--help
-h
help
-?
/?
SSH
Aka Secure SHell
# Run command on $HOST as $USER (default command=shell)ssh $USER@$HOST command# Run GUI command on $HOSTNAME as $USERssh-f-Y $USER@$HOSTNAME xeyes# Copy with permissions to $USER's home directory on $HOSTscp-p-r $USER@$HOST:filedir/# Use faster crypto for local LAN. This might saturate GigEscp-carcfour $USER@$LANHOST:bigfile# Forward connections to $HOSTNAME:8080 out to $HOST:80ssh-g-L8080:localhost:80root@$HOST# Forward connections from $HOST:1434 in to imap:143ssh-R1434:imap:143root@$HOST# Install public key for $USER@$HOST for password-less log inssh-copy-id $USER@$HOST
To disallow SSH remote root login, in /etc/ssh/sshd_config update/add:
# If `-f filename` is not defined, will generate 2 files (by default `~/.ssh/id_rsa` and `~/.ssh/id_rsa.pub`)ssh-keygen-trsa-b4096-f~/.ssh/user@host_rsassh-keygen-trsa-b4096-C"your_email@example.com"-f~/.ssh/your_email@example.com_rsassh-keygen-trsa-b4096-C"your_email@example.com"-f~/.ssh/your_email@example.com-hostname.ext_rsa
In ~/.ssh/config:
# username@hostname
Host hostname
RSAAuthentication yes
IdentityFile ~/.ssh/username@hostname_rsa
User username