Ctrl + n : same as Down arrow. Ctrl + p : same as Up arrow. Ctrl + r : begins a backward search through command history.(keep pressing Ctrl + r to move backward) Ctrl + s : to stop output to terminal. Ctrl + q : to resume output to terminal after Ctrl + s. Ctrl + a : move to the beginning of line. Ctrl + e : move to the end of line. Ctrl + d : if you've type something, Ctrl + d deletes the character under the cursor, else, it escapes the current shell. Ctrl + k : delete all text from the cursor to the end of line. Ctrl + x + backspace : delete all text from the beginning of line to the cursor. Ctrl + t : transpose the character before the cursor with the one under the cursor, press Esc + t to transposes the two words before the cursor. Ctrl + w : cut the word before the cursor; then Ctrl + y paste it Ctrl + u : cut the line before the cursor; then Ctrl + y paste it Ctrl + _ : undo typing. Ctrl + l : equivalent to clear. Ctrl + x + Ctrl + e : launch editor defined by $EDITOR to input your command. Useful for multi-line commands.
Change case
1 2 3 4 5 6
Esc + u # converts text from cursor to the end of the word to uppercase. Esc + l # converts text from cursor to the end of the word to lowercase. Esc + c # converts letter under the cursor to uppercase, rest of the word to lowercase.
Run history number (e.g. 53)
1
!53
Run last command
1 2 3
!! # run the previous command using sudo sudo !!
Run last command and change some parameter using caret substitution (e.g. last command: echo ‘aaa’ -> rerun as: echo ‘bbb’)
1 2 3 4 5 6 7 8 9 10 11
#last command: echo 'aaa' ^aaa^bbb
#echo 'bbb' #bbb
#Notice that only the first aaa will be replaced, if you want to replace all 'aaa', use ':&' to repeat it: ^aaa^bbb^:& #or !!:gs/aaa/bbb/
Run past command that began with (e.g. cat filename)
1 2 3 4
!cat # or !c # run cat filename again
Bash globbing
1 2 3 4 5 6 7 8 9 10 11
# '*' serves as a "wild card" for filename expansion. /etc/pa*wd #/etc/passwd
# '?' serves as a single-character "wild card" for filename expansion. /b?n/?at #/bin/cat
# '[]' serves to match the character from a range. ls -l [a-z]* #list all files with alphabet in its filename.
# '{}' can be used to match filenames with more than one patterns ls *.{sh,py} #list all .sh and .py files
Some handy environment variables
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
$0 :name of shell or shell script. $1, $2, $3, ... :positional parameters. $# :number of positional parameters. $? :most recent foreground pipeline exit status. $- :current options set for the shell. $$ :pid of the current shell (not subshell). $! :is the PID of the most recent background command.
$DESKTOP_SESSION current display manager $EDITOR preferred text editor. $LANG current language. $PATH list of directories to search for executable files (i.e. ready-to-run programs) $PWD current directory $SHELL current shell $USER current username $HOSTNAME current hostname
# foo=bar echo$foo # bar echo"$foo" # bar # single quotes cause variables to not be expanded echo'$foo' # $foo # single quotes within double quotes will not cancel expansion and will be part of the output echo"'$foo'" # 'bar' # doubled single quotes act as double quotes making variables expand echo''$foo'' # bar
Get the length of variable
1 2 3
var="some string" echo${#var} # 11
Get the first character of the variable
1 2 3 4 5 6
var=string echo"${var:0:1}" #s
# or echo${var%%"${var#?}"}
Remove the first or last string from variable
1 2 3
var="some string" echo${var:2} #me string
Replacement (e.g. remove the first leading 0 )
1 2 3
var="0050" echo${var[@]#0} #050
Replacement (e.g. replace ‘a’ with ‘,’)
1
{var/a/,}
Replace all (e.g. replace all ‘a’ with ‘,’)
1
{var//a/,}
Grep lines with strings from a file (e.g. lines with ‘stringA or ‘stringB’ or ‘stringC’)
1 2 3 4
#with grep test="stringA stringB stringC" grep ${test// /\\\|} file.txt # turning the space into 'or' (\|) in grep
To change the case of the string stored in the variable to lowercase (Parameter Expansion)
sed "/bbo/d" filename # case insensitive: sed "/bbo/Id" filename
Remove lines whose nth character not equal to a value (e.g. 5th character not equal to 2)
1 2 3
sed -E '/^.{5}[^2]/d' #aaaa2aaa (you can stay) #aaaa1aaa (delete!)
Edit infile (edit and save to file), (e.g. deleting the lines with ‘bbo’ and save to file)
1
sed -i "/bbo/d" filename
When using variable (e.g. $i), use double quotes “ “
1 2 3 4
# e.g. add >$i to the first line (to make a bioinformatics FASTA file) sed "1i >$i" # notice the double quotes! in other examples, you can use a single quote, but here, no way! # '1i' means insert to first line
Using environment variable and end-of-line pattern at the same time.
1 2
# Use backslash for end-of-line $ pattern, and double quotes for expressing the variable sed -e "\$s/\$/\n+--$3-----+/"
Delete/remove empty lines
1 2 3 4 5
sed '/^\s*$/d'
# or
sed '/^$/d'
Delete/remove last line
1
sed '$d'
Delete/remove last character from end of file
1
sed -i '$ s/.$//' filename
Add string to beginning of file (e.g. “[“)
1
sed -i '1s/^/[/' file
Add string at certain line number (e.g. add ‘something’ to line 1 and line 3)
1
sed -e '1isomething' -e '3isomething'
Add string to end of file (e.g. “]”)
1
sed '$s/$/]/' filename
Add newline to the end
1
sed '$a\'
Add string to beginning of every line (e.g. ‘bbo’)
1
sed -e 's/^/bbo/' file
Add string to end of each line (e.g. “}”)
1
sed -e 's/$/\}\]/' filename
Add \n every nth character (e.g. every 4th character)
1
sed 's/.\{4\}/&\n/g'
Concatenate/combine/join files with a separator and next line (e.g separate by “,”)
1
sed -s '$a,' *.json > all.json
Substitution (e.g. replace A by B)
1
sed 's/A/B/g' filename
Substitution with wildcard (e.g. replace a line start with aaa= by aaa=/my/new/path)
1
sed "s/aaa=.*/aaa=\/my\/new\/path/g"
Select lines start with string (e.g. ‘bbo’)
1
sed -n '/^@S/p'
Delete lines with string (e.g. ‘bbo’)
1
sed '/bbo/d' filename
Print/get/trim a range of line (e.g. line 500-5000)
1
sed -n 500,5000p filename
Print every nth lines
1 2 3
sed -n '0~3p' filename
# catch 0: start; 3: step
Print every odd # lines
1
sed -n '1~2p'
Print every third line including the first line
1
sed -n '1p;0~3p'
Remove leading whitespace and tabs
1 2
sed -e 's/^[ \t]*//' # Notice a whitespace before '\t'!!
Remove only leading whitespace
1 2 3
sed 's/ *//'
# notice a whitespace before '*'!!
Remove ending commas
1
sed 's/,$//g'
Add a column to the end
1 2 3 4 5
sed "s/$/\t$i/" # $i is the valuable you want to add
# To add the filename to every last column of the file for i in $(ls);do sed -i "s/$/\t$i/"$i;done
Add extension of filename to last column
1
for i in T000086_1.02.n T000086_1.02.p;do sed "s/$/\t${i/*./}/"$i;done >T000086_1.02.np
Remove newline\ nextline
1
sed ':a;N;$!ba;s/\n//g'
Print a particular line (e.g. 123th line)
1
sed -n -e '123p'
Print a number of lines (e.g. line 10th to line 33 rd)
1
sed -n '10,33p' <filename
Change delimiter
1
sed 's=/=\\/=g'
Replace with wildcard (e.g A-1-e or A-2-e or A-3-e….)
1
sed 's/A-.*-e//g' filename
Remove last character of file
1
sed '$ s/.$//'
Insert character at specified position of file (e.g. AAAAAA –> AAA#AAA)
Add string to the beginning of a column (e.g add “chr” to column $3)
1
awk 'BEGIN{OFS="\t"}$3="chr"$3'
Remove lines with string (e.g. ‘bbo’)
1
awk '!/bbo/' file
Remove last column
1
awk 'NF{NF-=1};1' file
Usage and meaning of NR and FNR
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# For example there are two files: # fileA: # a # b # c # fileB: # d # e awk 'print FILENAME, NR,FNR,$0}' fileA fileB # fileA 1 1 a # fileA 2 2 b # fileA 3 3 c # fileB 4 1 d # fileB 5 2 e
AND gate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# For example there are two files: # fileA: # 1 0 # 2 1 # 3 1 # 4 0 # fileB: # 1 0 # 2 1 # 3 0 # 4 1
# when using a backtick rm `find . -name "*.html"`
Delete files with whitespace in filename (e.g. “hello 2001”)
1
find . -name "*.c" -print0|xargs -0 rm -rf
Show limits on command-line length
1 2 3 4 5 6 7 8
xargs --show-limits # Output from my Ubuntu: # Your environment variables take up 3653 bytes # POSIX upper limit on argument length (this system): 2091451 # POSIX smallest allowable upper limit on argument length (all systems): 4096 # Maximum length of command we could actually use: 2087798 # Size of command buffer we are actually using: 131072 # Maximum parallelism (--max-procs must be no greater): 2147483647
ls |sed 's/.txt//g'|xargs -n1 -I file sed -i -e '1 i\>file\' file.txt
Count all files
1
ls |xargs -n1 wc -l
Turn output into a single line
1
ls -l| xargs
Count files within directories
1 2
echo mso{1..8}|xargs -n1 bash -c 'echo -n "$1:"; ls -la "$1"| grep -w 74 |wc -l' -- # "--" signals the end of options and display further option processing
Count lines in all file, also count total lines
1
ls|xargs wc -l
Xargs and grep
1
cat grep_list |xargs -I{} grep {} filename
Xargs and sed (replace all old ip address with new ip address under /etc directory)
1
grep -rl '192.168.1.111' /etc | xargs sed -i 's/192.168.1.111/192.168.2.111/g'
# if and else loop for string matching if [[ "$c" == "read" ]]; then outputdir="seq"; else outputdir="write" ; fi
# Test if myfile contains the string 'test': if grep -q hello myfile; thenecho -e "file contains the string!" ; fi
# Test if mydir is a directory, change to it and do other stuff: ifcd mydir; then echo'some content' >myfile else echo >&2 "Fatal error. This script requires mydir." fi
# if variable is null if [ ! -s "myvariable" ]; thenecho -e "variable is null!" ; fi #True of the length if "STRING" is zero.
# Using test command (same as []), to test if the length of variable is nonzero test -n "$myvariable" && echo myvariable is "$myvariable" || echo myvariable is not set
# Test if file exist if [ -e 'filename' ] then echo -e "file exists!" fi
# Test if file exist but also including symbolic links: if [ -e myfile ] || [ -L myfile ] then echo -e "file exists!" fi
# Test if the value of x is greater or equal than 5 if [ "$x" -ge 5 ]; thenecho -e "greater or equal than 5!" ; fi
# Test if the value of x is greater or equal than 5, in bash/ksh/zsh: if ((x >= 5)); thenecho -e "greater or equal than 5!" ; fi
# Use (( )) for arithmetic operation if ((j==u+2)); thenecho -e "j==u+2!!" ; fi
# Use [[ ]] for comparison if [[ $age -gt 21 ]]; thenecho -e "forever 21!!" ; fi
# Echo the file name under the current directory for i in $(ls); doecho file $i;done #or for i in *; doecho file $i; done
# Make directories listed in a file (e.g. myfile) fordirin $(<myfile); domkdir$dir; done
# Press any key to continue each loop for i in $(cat tpc_stats_0925.log |grep failed|grep -o '\query\w\{1,2\}');docat${i}.log; read -rsp $'Press any key to continue...\n' -n1 key;done
# Print a file line by line when a key is pressed, oifs="$IFS"; IFS=$'\n'; for line in $(cat myfile); do ...; done whileread -r line; do ...; done <myfile
#If only one word a line, simply for line in $(cat myfile); doecho$line; read -n1; done
#Loop through an array for i in"${arrayName[@]}"; doecho$i;done
While loop,
1 2 3 4 5 6 7 8 9
# Column subtraction of a file (e.g. a 3 columns file) whileread a b c; doecho $(($c-$b));done < <(head filename) #there is a space between the two '<'s
# Sum up column subtraction i=0; whileread a b c; do ((i+=$c-$b)); echo$i; done < <(head filename)
# Keep checking a running process (e.g. perl) and start another new process (e.g. python) immediately after it. (BETTER use the wait command! Ctrl+F 'wait') while [[ $(pidof perl) ]];doecho f;sleep 10;done && python timetorunpython.py
# or date +'%d-%b-%Y-%H:%M:%S' # 10-Apr-2020-21:54:40
# Returns the current time with nanoseconds. date +"%T.%N" # 11:42:18.664217000
# Get the seconds since epoch (Jan 1 1970) for a given date (e.g Mar 16 2021) date -d "Mar 16 2021" +%s # 1615852800 # or date -d "Tue Mar 16 00:00:00 UTC 2021" +%s # 1615852800
# Convert the number of seconds since epoch back to date date --date @1615852800 # Tue Mar 16 00:00:00 UTC 2021
wait for random duration (e.g. sleep 1-5 second, like adding a jitter)
1
sleep $[ ( $RANDOM % 5 ) + 1 ]
Log out your account after a certain period of time (e.g 10 seconds)
1 2
TMOUT=10 #once you set this variable, logout timer start running!
Set how long you want to run a command
1 2
#This will run the command 'sleep 10' for only 1 second. timeout 1 sleep 10
Set when you want to run a command (e.g 1 min from now)
1 2 3 4 5
at now + 1min #time-units can be minutes, hours, days, or weeks warning: commands will be executed using /bin/sh at> echo hihigithub >~/itworks at> <EOT> # press Ctrl + D to exit job 1 at Wed Apr 18 11:16:00 2018
Download the content of this README.md (the one your are viewing now)
1 2 3 4 5 6 7 8 9 10
curl https://raw.githubusercontent.com/onceupon/Bash-Oneliner/master/README.md | pandoc -f markdown -t man | man -l -
# or w3m (a text based web browser and pager) curl https://raw.githubusercontent.com/onceupon/Bash-Oneliner/master/README.md | pandoc | w3m -T text/html
# or using emacs (in emac text editor) emacs --eval'(org-mode)' --insert <(curl https://raw.githubusercontent.com/onceupon/Bash-Oneliner/master/README.md | pandoc -t org)
# or using emacs (on terminal, exit using Ctrl + x then Ctrl + c) emacs -nw --eval'(org-mode)' --insert <(curl https://raw.githubusercontent.com/onceupon/Bash-Oneliner/master/README.md | pandoc -t org)
# -r: recursive and download all links on page # -l1: only one level link # -H: span host, visit other hosts # -t1: numbers of retries # -nd: don't make new directories, download to here # -N: turn on timestamp # -nd: no parent # -A: type (separate by ,) # -e robots=off: ignore the robots.txt file which stop wget from crashing the site, sorry example.com
# Upload a file (e.g. filename.txt): curl --upload-file ./filename.txt https://transfer.sh/filename.txt # the above command will return a URL, e.g: https://transfer.sh/tG8rM/filename.txt
# Next you can download it by: curl https://transfer.sh/tG8rM/filename.txt -o filename.txt
Download file if necessary
1 2 3 4 5 6
data=file.txt url=http://www.example.com/$data if [ ! -s $data ];then echo"downloading test data..." wget $url fi
Wget to a filename (when a long name)
1
wget -O filename "http://example.com"
Wget files to a folder
1
wget -P /path/to/directory "http://example.com"
Instruct curl to follow any redirect until it reaches the final destination:
# List yum history (e.g install, update) sudo yum history # Example output: # Loaded plugins: extras_suggestions, langpacks, priorities, update-motd # ID | Login user | Date and time | Action(s) | Altered # ------------------------------------------------------------------------------- # 11 | ... <myuser> | 2020-04-10 10:57 | Install | 1 P< # 10 | ... <myuser> | 2020-03-27 05:21 | Install | 1 >P # 9 | ... <myuser> | 2020-03-05 11:57 | I, U | 56 *< # ...
# Show more details of a yum history (e.g. history #11) sudo yum history info 11
# Undo a yum history (e.g. history #11, this will uninstall some packages) sudo yum history undo 11
Audit files to see who made changes to a file [RedHat based system only]
1 2 3 4 5 6
# To audit a directory recursively for changes (e.g. myproject) auditctl -w /path/to/myproject/ -p wa
# If you delete a file name "VIPfile", the deletion is recorded in /var/log/audit/audit.log sudo grep VIPfile /var/log/audit/audit.log #type=PATH msg=audit(1581417313.678:113): item=1 name="VIPfile" inode=300115 dev=ca:01 mode=0100664 ouid=1000 ogid=1000 rdev=00:00 nametype=DELETE cap_fp=0000000000000000 cap_fi=0000000000000000 cap_fe=0 cap_fver=0
ssh-copy-id <user_name>@<server_IP> # then you need to enter the password # and next time you won't need to enter password when ssh to that user
Copy default public key to remote user using the required private key (e.g. use your mykey.pem key to copy your id_rsa.pub to the remote user)
1 2 3
# before you need to use mykey.pem to ssh to remote user. ssh-copy-id -i ~/.ssh/id_rsa.pub -o "IdentityFile ~/Downloads/mykey.pem" <user_name>@<server_IP> # now you don't need to use key to ssh to that user.
SSH Agent Forwarding
1 2 3 4 5 6
# To bring your key with you when ssh to serverA, then ssh to serverB from serverA using the key. ssh-agent ssh-add /path/to/mykey.pem ssh -A <username>@<IP_of_serverA> # Next you can ssh to serverB ssh <username>@<IP_of_serverB>
Set the default user and key for a host when using SSH
1 2 3 4 5 6
# add the following to ~/.ssh/config Host myserver User myuser IdentityFile ~/path/to/mykey.pem
# Next, you could run "ssh myserver" instead of "ssh -i ~/path/to/mykey.pem myuser@myserver"
Follow the most recent logs from service
1
journalctl -u <service_name> -f
Eliminate the zombie
1 2 3 4 5 6 7
# A zombie is already dead, so you cannot kill it. You can eliminate the zombie by killing its parent. # First, find PID of the zombie ps aux| grep 'Z' # Next find the PID of zombie's parent pstree -p -s <zombie_PID> # Then you can kill its parent and you will notice the zombie is gone. sudo kill 9 <parent_PID>
Show memory usage
1 2
free -c 10 -mhs 1 # print 10 times, at 1 second interval
Display CPU and IO statistics for devices and partitions.
1 2
# refresh every second iostat -x -t 1
Display bandwidth usage on an network interface (e.g. enp175s0f0)
1
iftop -i enp175s0f0
Tell how long the system has been running and number of users
1
uptime
Check if it’s root running
1 2 3 4
if [ "$EUID" -ne 0 ]; then echo"Please run this as root" exit 1 fi
Display file status (size; access, modify and change time, etc) of a file (e.g. filename.txt)
1
stat filename.txt
Snapshot of the current processes
1
ps aux
Display a tree of processes
1
pstree
Find maximum number of processes
1
cat /proc/sys/kernel/pid_max
Print or control the kernel ring buffer
1
dmesg
Show IP address
1 2 3 4
$ip add show
# or ifconfig
Print previous and current SysV runlevel
1 2 3 4
runlevel
# or who -r
Change SysV runlevel (e.g. 5)
1 2 3
init 5 #or telinit 5
Display all available services in all runlevels,
1 2
chkconfig --list # update-rc.d equivalent to chkconfig in ubuntu
Check system version
1
cat /etc/*-release
Linux Programmer’s Manuel: hier- description of the filesystem hierarchy
1
man hier
Control the systemd system and service manager
1 2 3 4 5
# e.g. check the status of cron service systemctl status cron.service
# e.g. stop cron service systemctl stop cron.service
List job
1
jobs -l
Run a program with modified priority (e.g. ./test.sh)
1 2 3 4 5
# nice value is adjustable from -20 (most favorable) to +19 # the nicer the application, the lower the priority # Default niceness: 10; default priority: 80
nice -10 ./test.sh
Export PATH
1
export PATH=$PATH:~/path/you/want
Make file executable
1 2
chmod +x filename # you can now ./filename to execute it
Print system information
1 2 3 4
uname -a
# Check system hardware-platform (x86-64) uname -i
Surf the net
1
links www.google.com
Add user, set passwd
1 2
useradd username passwd username
Edit PS1 variable for bash (e.g. displaying the whole path)
1 2 3 4 5 6
1. vi ~/.bash_profile 2. export PS1='\u@\h:\w\$' # $PS1 is a variable that defines the makeup and style of the command prompt # You could use emojis and add timestamp to every prompt using the following value: # export PS1="\t@🦁:\w\$ " 3. source ~/.bash_profile
Edit environment setting (e.g. alias)
1 2 3
1. vi ~/.bash_profile 2. alias pd="pwd" //no more need to type that 'w'! 3. source ~/.bash_profile
Print all alias
1
alias -p
Unalias (e.g. after alias ls=’ls –color=auto’)
1
unaliasls
Set and unset shell options
1 2 3 4 5 6 7 8
# print all shell options shopt
# to unset (or stop) alias shopt -u expand_aliases
# to set (or start) alias shopt -s expand_aliases
List environment variables (e.g. PATH)
1 2
echo$PATH # list of directories separated by a colon
ln -s /path/to/program /home/usr/bin # must be the whole path to the program
Show hexadecimal view of data
1
hexdump -C filename.class
Jump to different node
1
rsh node_name
Check port (active internet connection)
1
netstat -tulpn
Print resolved symbolic links or canonical file names
1
readlink filename
Find out the type of command and where it link to (e.g. python)
1 2 3 4 5 6 7 8 9 10 11 12
type python # python is /usr/bin/python # There are 5 different types, check using the 'type -f' flag # 1. alias (shell alias) # 2. function (shell function, type will also print the function body) # 3. builtin (shell builtin) # 4. file (disk file) # 5. keyword (shell reserved word)
# You can also use `which` which python # /usr/bin/python
List all functions names
1
declare -F
List total size of a directory
1 2 3 4
du -hs .
# or du -sb
Copy directory with permission setting
1
cp -rp /path/to/directory
Store current directory
1 2 3 4 5 6 7
pushd .
# then pop popd
#or use dirs to display the list of currently remembered directories. dirs -l
ssh -f -L 9000:targetservername:8088 root@192.168.14.72 -N #-f: run in background; -L: Listen; -N: do nothing #the 9000 of your computer is now connected to the 8088 port of the targetservername through 192.168.14.72 #so that you can see the content of targetservername:8088 by entering localhost:9000 from your browser.
Get process ID of a process (e.g. sublime_text)
1 2 3 4 5 6 7 8 9 10 11
#pidof pidof sublime_text
#pgrep, you don't have to type the whole program name pgrep sublim
#pgrep, echo 1 if process found, echo 0 if no such process pgrep -q sublime_text && echo 1 || echo 0
#top, takes longer time top|grep sublime_text
Some benchmarking tools for your server
aio-stress - AIO benchmark. bandwidth - memory bandwidth benchmark. bonnie++ - hard drive and file system performance benchmark. dbench - generate I/O workloads to either a filesystem or to a networked CIFS or NFS server. dnsperf - authorative and recursing DNS servers. filebench - model based file system workload generator. fio - I/O benchmark. fs_mark - synchronous/async file creation benchmark. httperf - measure web server performance. interbench - linux interactivity benchmark. ioblazer - multi-platform storage stack micro-benchmark. iozone - filesystem benchmark. iperf3 - measure TCP/UDP/SCTP performance. kcbench - kernel compile benchmark, compiles a kernel and measures the time it takes. lmbench - Suite of simple, portable benchmarks. netperf - measure network performance, test unidirectional throughput, and end-to-end latency. netpipe - network protocol independent performance evaluator. nfsometer - NFS performance framework. nuttcp - measure network performance. phoronix-test-suite - comprehensive automated testing and benchmarking platform. seeker - portable disk seek benchmark. siege - http load tester and benchmark. sockperf - network benchmarking utility over socket API. spew - measures I/O performance and/or generates I/O load. stress - workload generator for POSIX systems. sysbench - scriptable database and system performance benchmark. tiobench - threaded IO benchmark. unixbench - the original BYTE UNIX benchmark suite, provide a basic indicator of the performance of a Unix-like system. wrk - HTTP benchmark.
# installation # It collects the data every 10 minutes and generate its report daily. crontab file (/etc/cron.d/sysstat) is responsible for collecting and generating reports. yum install sysstat systemctl start sysstat systemctl enable sysstat
# show CPU utilization 5 times every 2 seconds. sar 2 5
# show memory utilization 5 times every 2 seconds. sar -r 2 5
# show paging statistics 5 times every 2 seconds. sar -B 2 5
# To generate all network statistic: sar -n ALL
# reading SAR log file using -f sar -f /var/log/sa/sa31|tail
# Found out server sensor temperature ipmitool sensors |grep -i Temp
# Reset BMC ipmitool bmc reset cold
# Prnt BMC network ipmitool lan print 1
# Setting BMC network ipmitool -I bmc lan set 1 ipaddr 192.168.0.55 ipmitool -I bmc lan set 1 netmask 255.255.255.0 ipmitool -I bmc lan set 1 defgw ipaddr 192.168.0.1
Send a ping with a limited TTL to 10 (TTL: Time-To-Live, which is the maximum number of hops that a packet can travel across the Internet before it gets discarded.)
1
ping 8.8.8.8 -t 10
Print the route packets trace to network host
1
traceroute google.com
Check connection to host (e.g. check connection to port 80 and 22 of google.com)
1 2 3 4 5 6
nc -vw5 google.com 80 # Connection to google.com 80 port [tcp/http] succeeded!
nc -vw5 google.com 22 # nc: connect to google.com port 22 (tcp) timed out: Operation now in progress # nc: connect to google.com port 22 (tcp) failed: Network is unreachable
Nc as a chat tool!
1 2 3 4 5 6
# From server A: $ sudo nc -l 80 # then you can connect to the 80 port from another server (e.g. server B): # e.g. telnet <server A IP address> 80 # then type something in server B # and you will see the result in server A!
Check which ports are listening for TCP connections from the network
1 2 3 4 5
#notice that some companies might not like you using nmap nmap -sT -O localhost
# check port 0-65535 nmap -p0-65535 localhost
Check if a host is up and scan for open ports, also skip host discovery.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#skips checking if the host is alive which may sometimes cause a false positive and stop the scan. $ nmap google.com -Pn
# Example output: # Starting Nmap 7.01 ( https://nmap.org ) at 2020-07-18 22:59 CST # Nmap scan report for google.com (172.217.24.14) # Host is up (0.013s latency). # Other addresses for google.com (not scanned): 2404:6800:4008:802::200e # rDNS record for 172.217.24.14: tsa01s07-in-f14.1e100.net # Not shown: 998 filtered ports # PORT STATE SERVICE # 80/tcp open http # 443/tcp open https # # Nmap done: 1 IP address (1 host up) scanned in 3.99 seconds
Scan for open ports and OS and version detection (e.g. scan the domain “scanme.nmap.org”)
1 2
$ nmap -A -T4 scanme.nmap.org # -A to enable OS and version detection, script scanning, and traceroute; -T4 for faster execution
Look up website information (e.g. name server), searches for an object in a RFC 3912 database.
# having two sorted and uniqed files (for example after running `$ sort -uo fileA fileA` and same for fileB): # ------ # fileA: # ------ # joey # kitten # piglet # puppy # ------ # fileB: # ------ # calf # chick # joey # puppy # # Find lines in both files comm -12 fileA fileB # joey # puppy # # Find lines in fileB that are NOT in fileA comm -13 fileA fileB # calf # chick # # Find lines in fileA that are NOT in fileB comm -23 fileA fileB # kitten # piglet
Number a file (e.g. fileA)
1 2 3 4 5 6 7 8 9
nl fileA
#or nl -nrz fileA # add leading zeros
#or nl -w1 -s ' ' # making it simple, blank separate
Join two files field by field with tab (default join by the first column of both file, and default separator is space)
1 2 3 4 5
# fileA and fileB should have the same ordering of lines. join -t '\t' fileA fileB
# Join using specified field (e.g. column 3 of fileA and column 5 of fileB) join -1 3 -2 5 fileA fileB
Combine/ paste two or more files into columns (e.g. fileA, fileB, fileC)
rename s/$/.txt/ * # You can use rename -n s/$/.txt/ * to check the result first, it will only print sth like this: # rename(a, a.txt) # rename(b, b.txt) # rename(c, c.txt)
Squeeze repeat patterns (e.g. /t/t –> /t)
1
tr -s "/t" < filename
Do not print nextline with echo
1
echo -e 'text here \c'
View first 50 characters of file
1
head -c 50 file
Cut and get last column of a file
1
cat file|rev | cut -d/ -f1 | rev
Add one to variable/increment/ i++ a numeric variable (e.g. $var)
1 2 3 4
((var++)) # or var=$((var+1))
Cut the last column
1
cat filename|rev|cut -f1|rev
Cat to a file
1 2 3 4
cat >myfile let me add sth here exit by control + c ^C
Clear the contents of a file (e.g. filename)
1
>filename
Append to file (e.g. hihi)
1
echo'hihi' >>filename
Working with json data
1 2 3 4
#install the useful jq package #sudo apt-get install jq #e.g. to get all the values of the 'url' key, simply pipe the json to the following jq command(you can use .[]. to select inner json, i.e jq '.[].url') cat file.json | jq '.url'
rsync -av directory user@ip_address:/path/to/directory.bak # skip files that are newer on receiver (i prefer this one!)
Make all directories at one time!
1 2 3
mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat} # -p: make parent directory # this will create project/doc/html/; project/doc/info; project/lib/ext ,etc
Run command only if another command returns zero exit status (well done)
1
cd tmp/ && tar xvf ~/a.tar
Run command only if another command returns non-zero exit status (not finish)
1
cd tmp/a/b/c ||mkdir -p tmp/a/b/c
Use backslash “" to break long command
1 2 3
cd tmp/a/b/c \ > || \ >mkdir -p tmp/a/b/c
List file type of file (e.g. /tmp/)
1 2
file /tmp/ # tmp/: directory
Writing Bash script (‘#!’’ is called shebang )
1 2 3
#!/bin/bash file=${1#*.} # remove string before a "."
Python simple HTTP Server
1 2 3
python -m SimpleHTTPServer # or when using python3: python3 -m http.server
Read user input
1 2
read input echo$input
Array
1 2 3 4 5 6 7
declare -a array=()
# or declare array=()
# or associative array declare -A array=()
Send a directory
1
scp -r directoryname user@ip:/path/to/send
Fork bomb
1 2 3 4
# Don't try this at home! # It is a function that calls itself twice every call until you run out of system resources. # A '# ' is added in front for safety reason, remove it when seriously you are testing it. # :(){:|:&};:
Use the last argument
1
!$
Check last exit code
1
echo $?
Extract .xz
1 2 3
unxz filename.tar.xz # then tar -xf filename.tar
Unzip tar.bz2 file (e.g. file.tar.bz2)
1
tar xvfj file.tar.bz2
Unzip tar.xz file (e.g. file.tar.xz)
1 2
unxz file.tar.xz tar xopf file.tar
Extract to a path
1
tar xvf -C /path/to/directory filename.gz
Zip the content of a directory without including the directory itself
1 2 3
# First cd to the directory, they run: zip -r -D ../myzipfile . # you will see the myzipfile.zip in the parent directory (cd ..)
Output a y/n repeatedly until killed
1 2 3 4 5 6 7 8 9 10 11
# 'y': yes
# or 'n': yes n
# or 'anything': yes anything
# pipe yes to other command yes | rm -r large_directory
Create large dummy file of certain size instantly (e.g. 10GiB)
1
fallocate -l 10G 10Gigfile
Create dummy file of certain size (e.g. 200mb)
1 2 3 4 5 6 7 8
ddif=/dev/zero of=//dev/shm/200m bs=1024k count=200 # or ddif=/dev/zero of=//dev/shm/200m bs=1M count=200
# Standard output: # 200+0 records in # 200+0 records out # 209715200 bytes (210 MB) copied, 0.0955679 s, 2.2 GB/s
Keep /repeatedly executing the same command (e.g Repeat ‘wc -l filename’ every 1 second)
1
watch -n 1 wc -l filename
Print commands and their arguments when execute (e.g. echo expr 10 + 20 )
1
set -x; echo `expr 10 + 20 `
Print some meaningful sentences to you (install fortune first)
1
fortune
Colorful (and useful) version of top (install htop first)
1
htop
Press any key to continue
1
read -rsp $'Press any key to continue...\n' -n1 key
Run sql-like command on files from terminal
1 2 3 4
# download: # https://github.com/harelba/q # example: q -d ",""select c3,c4,c5 from /path/to/file.txt where c3='foo' and c5='boo'"
# Send command to all panes in tmux: Ctrl-B :setw synchronize-panes
# Some tmux pane control commands: Ctrl-B # Panes (splits), Press Ctrl+B, then input the following symbol: # % horizontal split # " vertical split # o swap panes # q show pane numbers # x kill pane # space - toggle between layouts
# Distribute Vertically (rows): select-layout even-vertical # or Ctrl+b, Alt+2
# Distribute horizontally (columns): select-layout even-horizontal # or Ctrl+b, Alt+1
# Scroll Ctrl-b then \[ then you can use your normal navigation keys to scroll around. Press q to quit scroll mode.
ls -1 # or list all, do not ignore entries starting with . ls -1a
Capture/record/save terminal output (capture everything you type and output)
1 2 3
script output.txt # start using terminal # to logout the screen session (stop saving the contents), type exit.
List contents of directories in a tree-like format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
tree # go to the directory you want to list, and type tree (sudo apt-get install tree) # output: # home/ # └── project # ├── 1 # ├── 2 # ├── 3 # ├── 4 # └── 5 #
# set level directories deep (e.g. level 1) tree -L 1 # home/ # └── project
Set up virtualenv(sandbox) for python
1 2 3 4 5 6 7 8 9 10 11 12
# 1. install virtualenv. sudo apt-get install virtualenv # 2. Create a directory (name it .venv or whatever name your want) for your new shiny isolated environment. virtualenv .venv # 3. source virtual bin source .venv/bin/activate # 4. you can check check if you are now inside a sandbox. type pip # 5. Now you can install your pip package, here requirements.txt is simply a txt file containing all the packages you want. (e.g tornado==4.5.3). pip install -r requirements.txt # 6. Exit virtual environment deactivate