Unix and Linux Commands¶
Last Update: 12/31/2019.
This is a collection of general *nix commands.
For commands of specific task (not found here), see the specific reference section of this website.
(For example, the commands about managing “file systems” are introduced at Linux File System — Docsnt documentation)
How to Use¶
This is not a tutorial.
See the table of contents and search for keyword (e.g. troubleshoot).
- Unix and Linux Commands
- How to Use
- Prologue
- Philosophies and Notes
- Basics
- Keyboard Shortcuts
- Navigation
- Files
- Directory
- Links
- Find
- Archive and Compress
- Help
- Previous Commands
- Input and Output
- Filters and Text Manipulation
- Date and Time
- Names
- Users
- Privileges and Permissions
- Process Management and Resource Monitor
- Network
- Free Cache
- Environment and Global Variables
- Scripting
- Schedule
- Run in a Shell
- Build and Install
- Debugging
- Popular Paths
- Uncanny Commands
- Message
- Hardware Information
- Disk and Filesystem
- Run levels
- Power
- Printers
- Gpg Signature
- Distribution Specific
- Miscellaneous
Prologue¶
Things are ordered from general fundamentals to specific tips.
Each category is a topic, a way to organize.
Philosophies and Notes¶
- Everything is a “file”, including the shell, the devices, the directories.
- Shell is very serious with spaces. Pay extra heed when writing scripts.
- The brackets are meaningful in bash, I used them to represent user input if not specified otherwise.
- Here is a small website for oneline commands.
The exit values of commands:
| Value | Status |
| ----- | ----------------- |
| 0 | success |
| non-0 | failure |
| 2 | incorrect usage |
| 127 | command not found |
Shell built-in vs external
- some commands are only built-in in shell (
man builtins
) - some are only external (actually the majority)
- others have both versions (e.g.
kill
)- one reason: avoid creating new process
help
command -V command
builtin kill
/bin/kill
Always read manual for the most authoritative help
man bash
Basics¶
Open current path using GUI file explorer
- Different systems have different file explorers, it’s hard for me to test each one
- See here for more
- Pay attention to the privileges, it’s generally not good to run as root
nautilus . # Ubuntu? nemo . dolphin . # Arch Linux?
Redirection and pipes
- Sometimes you want to save output of a command as a file
- Or you want to use a file as input of a command
- Or you want to use output of a command as input of another file
- different streams (FD):
- 0: stdin
- 1: stdout, default for
>
and>>
- 2: stderr
/dev/null
is a magic file, everything redirected to it is magically discarded- order of redirection does not matter
# a.txt will be cleared and only consist of this line echo "write this line into file a.txt" > a.txt # the original content of a.txt would not be affected echo "append this line into file a.txt" >> a.txt # feed a small c program that reads input from STDIN with test_input ./a.out < test_input # store the errors and discard the standard output ./a.out 2>> err_log 1> /dev/null # two streams go to the same destination (2 is tied with 1) ./a.out > afile 2>&1 # order does not matter > count.txt 2> log.txt wc < shakespeare.txt # only output lines containing "file" man cat | grep file # list all files in root directory and output only the last 10 lines ls -lha / | tail -n 10 cat << TerminationSign > asdfdas > asdfdsa > TerminationSign (can be anything) cat << END > ShortScript.sh > #!/bin/bash > echo "I love bash" > END
Escape and back quote
- to escape bash keywords,
\
- to use the output of a command, shell will treat strings inside `` as commands
echo -e "bash\tis\tgood!" echo `echo "I like bash!"`
- to escape bash keywords,
Test and true and false
- true or false
- ‘[’ is the same as test
test true false
Change shell mode
set -o vi # set vi mode
Multiple lines
- use ‘;’ to run multiple commands in one line
- use ‘\’ to separate one-line commands
- note that you will see the so-called second prompt (PS2) here, usually “>”
echo this; echo that echo "this \ that"
Comments
#
Quote
"" # weak quote # $var are variables # back quotes and escape characters are processed '' # strong quote, everything is string `` # back quote, the primary output of the command inside with replace this string
Aliases
- alias is just shortcuts or macros
- use \ at the beginning of a command to un-alias
alias "rm -rf"="echo 'rm? how dare you?'" \rm -rf ./*.class
Expansions
- Shell Expansions (Bash Reference Manual)
- Magics about
$
: Shell Parameter Expansion - Filename Expansion
- process substitution is to substitute a command with a filename
- process being substituted are run async
- “Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files”
- Process Substitution
echo $( date ) # substitute with the command output # spawn a new process, that process write to stdout, current process reads from that stdout mkdir -v ~/{old,new} # creates ~/old, ~/new echo {1..10} echo ~user # home directory of 'user' echo ~+ # $PWD echo $(( 1+1 )) # https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html str=1234abcd echo ${str:1:2} # substring echo ${str: -1:2} # negative offset must have a space to avoid confusion with ${parameter:-word} # case conversion (pattern should be matching one char only) str=aabbccdd echo ${str^a} # convert the first char, if matched with pattern, to upper case echo ${str^^a} # convert all str=AABBCCDD echo ${str,a} # lower case echo ${str,,a} set -- a b c d e f g 1 2 3 4 # set the positional parameters, $1 $2 etc. array=(1 2 3 4 a b c d e f g) echo ${#str} # length of string echo ${#@} echo ${#*} # length of positional parameters echo ${#array[@]} echo ${#array[*]} # length of array # ... read more https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html # process substitution echo <(echo "bash love") echo < <(echo "bash love") echo "bash love" > >(cat)
Keyboard Shortcuts¶
^
stands for Ctrl
Abort (SIGINT)
^c
Suspend (signal 17, SIGTSTP)
^z
Go to the beginning of line
^a
Go to the end of line
^e
Delete content after cursor
^k
Clear the screen
^l
Log out current session
^d
Search in the history
^r
Autocompletion of commands or paths (Press twice to see all available ones if not unique)
- maybe it’s required to type a letter first then press
Tab
twice?
[Tab]
- maybe it’s required to type a letter first then press
Go to last command
[Up Arrow]
Fetch the parameters of last command
- Press together
[Esc]+.
Pause/Freeze the terminal
^s
Resume the terminal
^q
For cursor movement, here is an excellent picture.
Files¶
Create blank file or update last-change time
- -r/–reference=FILE use another file’s time as reference
- -a only change the access time
- -m only the modification time
- -c/–no-create do not create new file
touch # create an empty file or update access and modification time touch -t [[CC]YY]MMDDhhmm[.ss] # change both access and modification time to specified time
See file type and char-set and other information
file file -i [file]
See file disk usage
- -h human-reading friendly
- -s sum
- -a all files not just directories
- -dN max-depth=N
du du -sh du -s * du -hs .[^.]* du -sch .[!.]* * | sort -h du -hd1 | sort -h du -ahd1 | sort -h
Copy
- -r dir
- -v verbose
- -p reserve time
cp [source] [target] scp [source] [target] # secure copy, copy across ssh and so on
rsync
- -n dry-run
- -a archive
- -v verbose
- -h human-friendly size
- -u update, skip newer files on the receiving side
- remove dry-run after checking the result
rsync -avh --dry-run <source> <target> # copy and overwrite, no deletion rsync -u -ah --dry-run <source> <target> # copy and overwrite for files that are newer in source
Move and rename
- -v verbose
mv
treats directories and files the same
mv [source] [target]
Delete
- -i interactive
- -r dir
- -f force
- rm -rf ./* delete all files in current dir
- su”do r”m -r”f /* Say goodbye to your system (Never run this!!!!!)
rm
Quota
quota -v
File system disk space usage
- troubleshoot
df df . df -k # use 1k as SIZE scale
Pay heed to the difference between du
and df
Directory¶
Create new dir
- -p Create parents if necessary
- -v verbose
mkdir mkdir -pv [name]
Remove empty dir
- Note: use “rm -r” to remove non-empty dir
rmdir rmdir -pv
Links¶
Crate a soft links
ln -s [source-file] [link]
Find¶
Find file by name using prebuilt databases
- Like pre-processing the files
- the database is updated per day by default
- cannot lookup the file changes after the last update
locate [pattern-to-find] updatedb # update the database, may be slow
Find
- Advanced find
- Specify the path
- More options
- Real-time scan
- path
- . current directory
- / root directory (all files)
- arguments
- -name [name]
- -perm [permissions]
- can only use octal representation
- -type
- d directory
- l link
- -user
- -group
- -ctime change time
- -size
- use the result to execute commands
- -exec
find [path] [arguments] # call ls -l on all files in current directory whose names start with 'a' find . -name "a*" -exec ls -l {} \; # search all files in current directory for pattern # and print the paths of those files find . -type f -print0 | xargs -0 grep "pattern" # only files, no paths find . -type f -print0 | xargs -0 grep -l "pattern"
Where is this command/program I’m executing?
which which which
Archive and Compress¶
How are zlib, gzip and zip related? What do they have in common and how are they different?
Zip and Unzip
zip [archive-file-name] [files-to-archive] zip a.zip a unzip file[.zip]
gzip and gunzip
- compress
gzip gunzip
tar
- archive only, no compress
- -c create
- -x extract
- -v verbose, can (should?) omit when there is a number of files
- -z gzip
- -f use archive file or device ARCHIVE
# archive a file tar -cvf [archive-file-name] [files-to-archive] tar -cvf a.tar a.b b.c tar -chof # h: follow symlinks o: Compatibility # archive and compress tar -cvzf [archive-file-name] [files-to-archive-and-compress] tar a.tar.gz a.b b.c # extract a archive tar -xvf [archive-file] tar -xvf a.tar # extract and uncompress tar -xvzf [compressed-archive-file name] tar -xvzf a.tar.gz # extract to different directory # the target director must exist tar -xvzf a.tar.gz -C [/target/directory]
Help¶
help
- Almost all commands have
help
option - It’s a summary of the usage
- This is always the first option before using an unfamiliar command
[command] -h [command] --help help [command] # a command called help, mainly for shell build-in commands
- Almost all commands have
man (manual)
- Explain a command
- If exists, more detailed than
help
- A detailed usage instruction
- You can even look up C language libraries
- Types (-s<TYPE_NUM>) (from
man man
)- 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]
- Ex: use
-s3
to check section 3 specifically- otherwise will lookup in the pre-defined order: “1 n l 8 3 2 3posix 3pm 3perl 5 4 9 6 7”
- or change here:
/etc/manpath.config
- -k [key word]
- search for all documentation with key word
man ascii man -s3 malloc # c function, i.e. the function within program lib man echo
info
- more detailed than man
doc
- txt, html, pdf
- stored at /usr/share/doc
What is this command (one-line description)
whatis
Forget how to spell a command
apropos
Previous Commands¶
See history
history
The event reference (!) is mainly used in scripts?
Run the last command
!!
Run the last command beginning with a specific letter
![specific letter]
Run the command by number in history (use
history
to see the number)![number]
Execute the command containing specific string
![specific_string]
Execute the nth preceding event (i.e. using a negative number for the index)
!-[number]
Last word of previous command
- Can be used to test if in same shell
- Safe way to rm
!$ ls xxx.yyy rm !$
Replace part of previous commands
- I think only few people know this
- sample command from @bashoneliners
# change encoding of all files in a directory and subdirectories find . -type f -name '*.java' -exec sh -c 'iconv -f cp1252 -t utf-8 "$1" > converted && mv converted "$1"' -- {} \; ^java^cpp # safe way to remove ls xxx ^ls^ rm -v
Input and Output¶
Display a line of text
- -n no new line at the end
- -e expand special characters and variables
echo echo "xxx" >> [file] echo "xxx" > [file] echo -e "$!"
Display all the content of one file
cat cat a.txt > b.txt
Display the head of one file
- -n Display the first n lines
head head -n 10
Display the tail of one file
- -n
- -f Follow the latest updates of one file (usually used to watch the log files)
- -F (recommended) same as -f but “keep trying to open a file if it is inaccessible”
- can track when renaming
- avoid confusion when logs are rotated
tail
Paging through text (downward only)
- q to quit
more
Paging through text
- q to quit
- less is more
less
Read input
read var_1 # type input echo "$var_1"
Watch a command, namely keep printing the output of a command
- -n interval
- -c color
watch -c -n 1 command
Copy stdin to multiple places
- -a –append append not overwrite
- -i –ignore-interrupts signals
- –output-error[=mode] change the error behavior, see man page
tee echo "some-huge-file" \ | tee some-huge-file.file | sha1sum > some-huge-file.sha1 tar -cvf - "a-file" \ | tee >(md5sum --tag) >(sha256sum --tag) > "a-file.tar"
Print printable strings
strings [some-file]
Filters and Text Manipulation¶
Search for specific pattern
- -i ignore case
- -n precede line numbers
- -v lines with no specific patterns
- -Ax include x lines after the pattern in output
- -Bx include x lines before the pattern in output
- What is the difference between
grep
,egrep
, andfgrep
?
grep [file] [string] pdfgrep # grep in pdf files
sort
- sort based on character or number
- use alphabet and numbers by default
- -r reverse
- -n sort numerically
- -f ignore case
- -u unique, remove duplicated lines
- -t SEP use SEP as delimiter/separator
- -k KEYDEF specify the key to use when sorting
ps -aef | sort > out.txt
Remove consecutive identical lines
- Usually needs to be sorted first
- -c precede line with number of repetitions
- -d only repeated lines
- -u only non-repeated lines
uniq
Word count
wc wc -l # lines wc -w # words wc -c # bytes wc -m # characters
diff
- output means the edits that is required to make file1 identical to file2
- append
- delete
- change
- ‘<’ means line from file1
- ‘>’ means line from file2
diff file1 file2 vimdiff
- output means the edits that is required to make file1 identical to file2
Cut text
- Used to process specific columns of the delimited text
- -d specify the delimiter, TAB by default
- -f specify the number of column to output
- -c cut based on characters
cut cut -b [bytes] # select only specified bytes cut -c 1-2, 3, 6 # characters cut -d ' ' # use ' ' as delimiter cut -d: -f1 /etc/passwd grep some-user /etc/passwd | cut -d: -f2,3,4 cut -c2-6 /etc/passwd # output from 2nd character to 6th character
Paste
- Merge lines of files
- like reverse of
cut
paste paste -d ' ' file1 file2 file3 > output
Check spelling
aspell aspell check <some-file> aspell list < <some-file>
Translate
- needs redirection
tr -d 'some-words' < <some-file> # delete some-words from some-file tr 'a-z' 'A-Z' < <some-file> # change case
Search and replace
- regular expression
- write to stdout
sed 's/aaa/bbb/g' <some-file> # replace 'aaa' with 'bbb', 'g' for global sed '1,50s/aaa/bbb/g' <some-file> # specify the lines sed -e 's/aaaa/bbb/g' -e 's/ccc/ddd/g' <some-file> sed -f <some-script> <some-file> # use a file as script
Date and Time¶
Show or set current date and time
- +%Y–%m–%d (e.g.)
- Print time in specific format
%
is the identifer
- -u Greenwich time
- -s setting
date
- +%Y–%m–%d (e.g.)
Show hardware time (time on the motherboard)
hwclock clock
Calendar
cal
Up time
- troubleshooting
- Output is consist with:
- uptime
- Login users
- load
- average number of processes in “run” or “ready” queue of 1 min, 5 min and 15 min
- note that machine may have more than one CPU
- 1 means 100% load for one CPU
- not that fantastic anymore since majority of systems run on multi-core CPUs
- also consider processes blocked due to I/O, shown as load
uptime
Names¶
System
uname uname -a
Host
hostname
Users¶
Switch user
- if empty, switch to root
su - [user]
Switch user and keep current path
- if empty, switch to root
su [user]
Run as root
sudo sudo -E # pass environment sudo SOME_VAR=SOME_VAL # pass variable sudo -i # a shell [sudo] SOME_CMD | sudo tee SOME_WRITE_FILE # redirection [sudo] SOME_CMD | sudo tee -a SOME_WRITE_FILE # redirection append
Log out
exit
Change password
passwd
User Id
id id 1000 # display info about user whose id is 1000
Who am I?
- The informal philosophy of commands: the shorter, the more information; the longer, the more specific.
whoami who w
Create and delete user
# add useradd adduser # a wrapper of useradd # passwd [user] # set password if not already # del deluser --remove-home [user] # Debian-based userdel -r [user] # RHEL-based
Manage group
groupadd addgroup # a wrapper of groupadd groupdel delgroup # a wrapper of groupdel newgrp [group] # change current group ID newgrp - [group] # with reinitialized environment newgrp # change to default group in /etc/passwd file
Fingers
finger [user] # display user's information if exists chfn # change finger
Administer commands
gpasswd # administer /etc/group and /etc/gshadow yppasswd # ? ypchfn # ?
Log out old sessions that was ‘broken’
pkill -u [username]
Last logged in user
- -a: display hostname in last column
- -i: display ip
last -5 last -5ai
Privileges and Permissions¶
ls -a
can list the permissions of a specific file.
Change mode
- The permissions in *nix is in U/G/O model
- The representations of permission is ordered by user/group/other
- There are 3 permissions of a file:
- r: read, 2^2=4
- w: write, 2^1=2
- x: execute, 2^0=1
- As you can see, the largest permission represented by an integer is the sum of them, 7
- Try not messing up with permissions until mastering them
- -R recursive change permission of all files in a directory
- -f force
- [ugo][+-=][rwx]
- Unix Permissions Calculator
- See other places or
man
for details - Note that the directories must have permission execute ‘opened’ to be opened
- r for directories: can read the list
- w for directories: create or remove files
- x for directories: can pass through
- There are other special permissions. For example, ‘s’ is the
setuid
bit, meaning that the user who issued the command did not change (no sudo) but the user receives the septics privileges, likepasswd
andping
.
chmod -R [directory] chmod -f ... chmod u+x [file] chmod ug-x [file] chmod 640 [file] chmod u+x,g-x [file] chmod u=rwx [file]
Change ownership
- -R: recursively change all subdirectories and files
chown some-user some-file chown -R some-user some-directory
SELinux (advanced way to manage permissions)
sestatus getenforce seinfo semanage setenforce 0 # put SELinux in permissive mode (Not Recommended) # SELinux policies will not take effects # but will log # and label newly created files # will reset after rebooting # modify one of the following files to disable /etc/grub.conf /etc/selinux/config
Default permission when creating a new file
- It’s negated (reversed)
- details
umask
Process Management and Resource Monitor¶
Run in background
[command]&
See processes in background
- Including the commands executed with
&
at the end - and the commands suspended using Ctrl+Z
jobs jobs -l
- Including the commands executed with
Put a process in background if not started with
&
, or resume suspended processes (SIGTSTP) in backgroundbg [ID]
Put a process back to foreground
- note the output may still be absent
fg [ID]
Modify scheduling priority of a program
- -20 is most favorable
- 19 is least favorable
nice -19 [command]
List processes
- troubleshoot
- See IDs of processes
- Read help of
ps
for details - e: all processes
- a: all processes except session leader and processes not associated with a terminal
- x: display session leader and processes not associated with a terminal (?)
- e = a + x ?
- u: userlist
- w: wide, use twice for unlimited width
ps ps ef # all processes ps aux # no parent process ID ps -ef | grep mysql | grep -v grep | awk '{print $2}' # lookup PID of mysql ps axuf ps auxww # output with unlimited width ps aux | grep -v grep | grep -i -e VSZ -e ps -e -o pid,vsz,comm= | sort -n -k 2 ps -C bash -o pid= # show pid of bash pidof bash # show pid of bash
Monitor processes
- troubleshoot
top
is very powerful- Interesting post: htop explained | peteris.rocks
pstree -a top htop slabtop
Send signals to process
- List of “sigspec” and “signum”:
- SIGHUP 1
- SIGINT 2
- SIGQUIT 3
- SIGFPE 8
- SIGKILL 9
- SIGALRM 14
- SIGTERM 15
- Use
kill -l
for more - process can ignore some signals
kill -l # send SIGTERM by default kill [id] kill -9 [id] # the kill signal cannot be ignored and immediately # skipping the "clean up" before dying kill -0 [id] # check if process exists or permission to signal exists # note that built-in kill is different from the external kill # http://man7.org/linux/man-pages/man2/kill.2.html kill -s [sig] 0 # send sig to every process in the process group of the calling process kill -s [sig] -1 # all processes except the kill process itself and init # If pid is less than -1, then sig is sent to every process in the process group whose ID is -pid.
- List of “sigspec” and “signum”:
Run commands that ignore some signals
trap [command list] [signal]
Do not kill command when log out
- Usually the processes have parents. As parents die, they die
- Sometimes we do not want so
- Linux: Prevent a background process from being stopped after closing SSH client
nohup [command] > /dev/null 2>&1 &
Show available memories
- troubleshoot
free free -h free -mt
Read syslog
- troubleshoot
sudo tail -F /var/log/syslog
system control
sudo systemctl status nginx sudo systemctl list-unit-files
Journals / logs
- troubleshoot
sudo journalctl -u docker -b # unit boot sudo journalctl -u docker -f # follow sudo journalctl -u docker --no-pager # print to stdout sudo journalctl -u docker --no-pager > ./some-log # and redirect to a file
Virtual Memory Stat
- troubleshoot
- r: running
- b: blocked
- io
- bi: Blocks In
- bo: Blocks Out
- in: interrupts
- cs: context switches
- cpu (in %)
- USer
- SYstem
- IDle
- Wait
- can leave it run for some time and see the trends
vmstat vmstat 1 # per second, output is 1 second average
IO Status
- troubleshoot
iostat iostat 1 # per 1 sec iostat -x
Trace Syscalls
- troubleshoot
strace [some-command] strace -e [some-key-word] [some-command]
Network¶
Net Status
- troubleshoot
netstat -s # show a sweet summary sudo netstat -lnp # show all open ports, including sockets sudo netstat -tupln # without sockets netstat -an # all and numerical netstat -tan # tcp netstat -tanep # extended and show program
Investigate sockets
sudo ss -lnp
List activating ports
lsof
Firewall / iptables
sudo iptables -Lnv sudo ip6tables -Lnv sudo dpkg-reconfigure iptables-persistent # iptablessave for debian # delete all rules sudo iptables -P INPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo iptables -P OUTPUT ACCEPT sudo ip6tables -P INPUT ACCEPT sudo ip6tables -P FORWARD ACCEPT sudo ip6tables -P OUTPUT ACCEPT sudo iptables -t nat -F sudo iptables -t mangle -F sudo iptables -F sudo iptables -X sudo ip6tables -t nat -F sudo ip6tables -t mangle -F sudo ip6tables -F sudo ip6tables -X
IP, interfaces, routes etc.
- check
man ip
ip ip route ip link show
- check
Enable bbr
echo "tcp_bbr" >> /etc/modules-load.d/modules.conf echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf sudo sysctl -p # test sudo sysctl net.ipv4.tcp_available_congestion_control sudo sysctl net.ipv4.tcp_congestion_control
Curl
curl --help curl --manual # GET curl [URL] # POST curl -d data=data [URL] curl --data data=data [URL] curl -d '{"json":"value"}' -H "Content-Type: application/json" [URL] curl --data-urlencode [data] [URL] # auto encode url for POST curl --form upload=@[file_name] --form press=[some_value] [URL] # RFC1867-posting upload file # HEAD curl --head [URL] curl -I [URL] # PUT curl --upload-file [some_file] [URL] # Get more details curl -i # include response headers curl --verbose curl -v # abbr for verbose # record everything sends and receives curl --trace [dump_file_name] curl --trace-ascii [dump_file_name] curl --trace-ascii [dump_file_name] --trace-time # output curl -o curl -O # multiple urls curl [URL1] [URL2] # send same request to multiple urls curl [URL1] --next -I [URL2] # send different requests to multiple urls # referer curl --referer [origin_url] [destination_url] # user agent curl --user-agent "user agent string" [URL] # follow redirection curl --location [URL] # Cookie curl -b # abbr for --cookie curl --cookie "data=data" [URL] # send cookie for GET curl --dump-header [cookie-dump-file] [URL] # record the cookies curl --cookie [previous-dumped-cookie] [URL] # user previous stored cookies # preferred way to store cookies, use non-exist file as --cookie parameter to enable cookie engine only curl --cookie [previous-cookie-file-name] --cookie-jar [new-cookie-file-name] [URL] # use old cookie and store new # https curl -k # abbr for --insecure curl --insecure # not verifying server-side certificates curl --cery some-cert-file.pem [https_URL] # use client-side certificate curl --cacert ca-bundle.pem [https_URL] # use CA store to verify server-side certificates # specify a ip address for a domain curl --resolve [some_domain]:[some_port]:[some_address] [same_domain] curl --proxy [some_proxy] [URL]
wget
- directly download a link
- q: quite
- O: output,
-
for stdout - P: prefix directory (will create sub-directory if non-exist)
wget 127.0.0.1/file.txt wget -qO- 127.0.0.1 wget -P ~/download/new-directory 127.0.0.1/files.txt
Actual Networking Traffic
- troubleshoot
tail -F /proc/net/dev iftop iptraf tcpdump # raw
Free Cache¶
How to Clear RAM Memory Cache, Buffer and Swap Space on Linux
How do you empty the buffers and cache on a Linux system?
Use slabtop display kernel slab cache information:
slabtop vmstat -m cat /proc/slabinfo
Drop buffer to free memory
sync
Drop cache
# as root usuer ## To free pagecache: echo 1 > /proc/sys/vm/drop_caches ## To free dentries and inodes echo 2 > /proc/sys/vm/drop_caches ## To free pagecache, dentries and inodes echo 3 > /proc/sys/vm/drop_caches # using sudo sudo sh -c 'echo 1 >/proc/sys/vm/drop_caches' sudo sh -c 'echo 2 >/proc/sys/vm/drop_caches' sudo sh -c 'echo 3 >/proc/sys/vm/drop_caches' ## or echo "echo 1 > /proc/sys/vm/drop_caches" | sudo sh
Environment and Global Variables¶
Get env/configs for system
printenv printenv | less set set | less getconf ARG_MAX set path = ($path ~/exe/bin)
Directly print current variables
echo $? # return value of last command echo "program name is: $0" echo "the first command line parameter is: $1" echo "there are $# command line parameters" echo "$@" # an array of command line parameters echo "$*" # a list of command line parameters echo "$$" # current process ID, if in a shell then shell's, if in a script then the process that is running the script echo "$BASHPID" # process ID of the current instance of bash echo "$BASH_SUBSHELL" # "subshell level", it's a variable echo "$!" # the process ID of the most recently executed background pipeline echo "$OSTYPE" echo "$USER" # your login name echo "$HOME" # the path name of your home directory echo "$HOST" # the name of the computer you are using echo "$ARCH" # the architecture of the computers processor echo "$DISPLAY" # the name of the computer screen to display X windows echo "$PRINTER" # the default printer to send print jobs echo "PATH" # the directories the shell should search to find a command
Scripting¶
Shell scripts need a shebang to be run directly, specifying its “caller” program
- the first line of scripts
- the only line beginning with # that is not a comment
- used to specify interpreter for common scripting languages like Python, Ruby
- same as using the filename as a argument of that command
- Why is it better to use “#!/usr/bin/env NAME” instead of “#!/path/to/NAME” as my shebang? (Not always)
#!/usr/bin/env bash
echo "this is a sample script file"
This is same as
/usr/bin/env bash [the-script-name]
Basic scripting
echo "program name is: $0" echo "the first command line parameter is: $1" echo "there are $# command line parameters" expr 2 + 3 echo $((2**3)) b=`expr $a+1` # no extra spaces array=(1 2 3) echo ${a[*]}; echo ${a[0]} x=3 echo $x unset x # delete x echo $x mydir=`pwd`; echo $mydir echo $1 echo "$1" # In general, use double quotes in case the variable is not defined
Write script on the fly
- capture all commands and save to a file
- Ctrl+D (EOF) to end
script
Expression and calculation
expr
commands supports:- arithmetic operators: +,-,*,/,%
- comparison operators: <, <=, ==, !=, >=, >
- boolean/logical operators: &&, ||
- parentheses: (, )
- precedence is the same as in C, Java
bc
is a precision calculating languageawk
can also be used to evaluate expressions
echo $((1+3)) if [ `expr 1 < 2` ]; then echo "yeah"; fi echo "scale=6;(1/12)+(7/13)" | bc echo "(1/12)+(7/13)" | bc -l awk "BEGIN {print -3.14 - -1.4141 * 3}"
Test
- since all variables in bash are strings, sometime you are actually comparing strings not numbers
- do not use “<” and so on to compare numbers
[[ ]]
and[ ]
is aliases for test to compare strings and numerical values[
is the same astest
and]
is just a special parameter for it[[ ]]
is bash extension
- Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?
- Other Comparison Operators
[[ string1 = string2 ]] # True if strings are identical, note only ONE equal sign [[ string1 == string2 ]] # Same as above [[ string1 != string2 ]] # True if strings are not identical [[ string ]] # Return 0 exit status (=true) if string is not null [[ -n string ]] # Return 0 exit status (=true) if string is not null [[ -z string ]] # Return 0 exit status (=true) if string is null [[ int1 –eq int2 ]] # Test identity [[ int1 –ne int2 ]] # Test inequality [[ int1 –lt int2 ]] # Less than [[ int1 –gt int2 ]] # Greater than [[ int1 –le int2 ]] # Less than or equal [[ int1 –ge int2 ]] # Greater than or equal test 1024 -eq 1024 # can use test directly if cond1 && cond2 || cond3 if cond1 –a cond22 –o cond3 if [ "$a" –lt 0 –o "$a" –gt 100 ] test -d file # if file is a directory test -f file # if file is not a directory test -s file # if the file has non zero length test -r file # if the file is readable test -w file # if the file is writable test -x file # if the file is executable test -o file # if the file is owned by the user test -e file # if the file exists test -z file # if the file has zero length
- since all variables in bash are strings, sometime you are actually comparing strings not numbers
Flow controls
if []; then echo "1" elif []; then echo "2" else echo "3" fi for i in 1 2 3 4 do echo i done while test "$i" -gt 0 do i=`expr $i - 1` done until test "$i" -lt 0 do i=`expr $i - 1` done status="off" input="on" case $argument in "on") echo "on" status="on";; "off") status="off" echo 3 ;; esac
Substring Operations
- Strip variables
- Replacement
statement="Bashhhhhh? BashBaassshhh!" echo "${statement#B*h}" # shortest from beginning # hhhhh? BashBaassshhh! echo "${statement##B*h}" # longest from beginning # ! echo "${statement%B*\!}" # shortest from ending # Bashhhhhh? Bash echo "${statement%%B*\!}" # longest from ending # (empty string) mydir=$(pwd) basename $mydir # only the last directory name dirname $mydir # no `basename` # replacement echo "${statement/hhh/HHH}" # replace first occurrence # BasHHHhhh? BashBaassshhh! echo "${statement/#Bash/HHH}" # replace front-end first occurrence echo "${statement/%hhh\!/HHH}" # replace back-end first occurrence echo "${statement//hhh/HHH}" # replace all occurrences # BasHHHHHH? BashBaasssHHH! echo "${statement//hhh/}" # remove all occurrences (replace with empty string) # Bas? BashBaasss!
Positional parameters
- either passed as command line args, from function calls, or set
- accessed via $0, $1, …
- $0 is the name of current script/function
- $# number of positional parameters or cmd line args
- “$*” must be quoted, all positional parameters as a single word
- “$@” should be quoted, all positional parameters as separated words, each as a quoted string without interpretation or expansion
- use shift to move them, i.e. $1 will hold the value of $2, $2 will be $3 and so forth
- $1 will be lost, $0 will not change
echo "$2" shift echo "$1" # same thing # read command line arguments while [[ $# > 0 ]];do key="$1" case $key in -n|--name) NAME="${2}" shift # we read 2 args ;; -h|--help) HELP="1" ;; -f|--force) FORCE="1" ;; *) # unknown echo "Invalid arg detected, aborting..." exit -1 ;; esac shift done
Exec
- 2 main usages
- redirect stdin and stdout
- replace current process with new process
- Using exec
- I/O Redirection
# stdin exec 6<&0 # Link file descriptor #6 with stdin. Saves stdin. exec < input-file # stdin replaced by file "input-file" read var # read first line in input-file to var exec 0<&6 6<&- # restore stdin from file descriptor #6 and free #6 exec <&6 6<&- # restore stdin from file descriptor #6 and free #6 # stdout exec 7>&1 # Link file descriptor #6 with stdout. Saves stdout. exec > output-file # stdout replaced by file "output-file". echo "Editing file" exec 1>&7 7>&- # Restore stdout and close file descriptor #7. # no extra process exec bash -l ps # new bash will have same process ID as current shell bash -l # create a new bash shell ps # will have (at least) 2 shell processes # subshell problem (inaccessible variables within a subshell) num=0 cat input | read num # first line of input is a non-zero number echo $num # num is still 0 # exec for subshell problem num=0 exec 3<> input # set file descriptor #3 to input, create if not exist read num <&3 echo $num # num is the number in input file
eval
- combine strings into a single command and execute
- useful if args are only known at run-time
help eval # read the usage help for your own shell eval echo -e $USER
array
- note that bash variables have no type
- strings
- Arrays
declare -a array # declare array as an array, not necessary in all cases # print whole array echo ${array[@]} echo ${array[*]} # difference is same as $@ vs $* # normal variables can use array operators str=123 echo ${#str[@]} # length is 1 echo ${str[0]} # will be 123 # literal init array=( {0..3} AAA ) echo ${array[@]} array[10]="This is the 10th elem of a sparse array" echo ${array[@]} echo ${!array[@]} # another init array=([1]=one [2]=two) echo ${array[@]} # read to array read -a inputs # can use variable as index idx=1 echo ${array[idx]} # same as ${array[0]} echo ${array} # for-each for elem in "${inputs[@]}" do echo $elem done # can use stirng operations, e.g. substring removal (strip) and replacement etc. echo ${array[@]#o*} echo ${array} # delete unset array[0] unset array
- note that bash variables have no type
Schedule¶
Chronos
crontab -e (crontab -l 2>/dev/null; echo "*/5 * * * * <some-job>") | crontab -
Chronons Job
- Edit current crontab after
crontab -e
- CronHowto - Community Help Wiki
- Cron format
- “In extended mode, crontab notation may be abridged by omitting the rightmost asterisks.”
Minute Hour DayOfMonth MonthOfYear DayOfWeek Year Command * * * * * * each minute 59 23 */2 * * each 2 day at 23:59 @reboot reboot 0 0-11 * Mon-Fri * each hour before 12 on weekdays
- Edit current crontab after
Run in a Shell¶
A shell
/bin/sh # Bourne Shell /bin/bash # bash /bin/csh # c shell /bin/tcsh # Turbo C Shell ksh # Korn shell
A script
- generally speaking, the difference is if the script is run under current shell or not
- read help for more
- BTW the “.sh” at the end is not necessary
./script.sh # chmod u+x ./script.sh # give user permission to execute the file if you want to run the script as the line above # if error, check if current user has execute permission . script.sh # born shell? source script.sh # c shell? sh script.sh bash script.sh
Secure Shell
- -C compress
- “Compression is desirable on modem lines and other slow connections, but will only slow down things on fast networks”
- -f SSH go background before execution
- -n redirects stdin from /dev/null (disable stdin), ssh will go background, not work if password needed
- -N do not execute a remote command, useful for forwarding
- -T disable pseudo-terminal allocation, useful for forwarding
- port forwarding
- How does reverse SSH tunneling work?
- local
- connections of SSH client forwarded via SSH server to destination server
- remote
- connections of SSH server forwarded via SSH client to destination server
- dynamic
- connections forwarded via SSH client and then SSH server to destination servers
- i.e. use SSH client as a SOCKS proxy server
- An article from dev.to - SSH Tunneling - Local, Remote & Dynamic
ssh ssh user@0.0.0.0 -p 22 # specify user, ip address, and port # port forwarding ## local ## localhost:8080 will be forwarded to www.example.com:80 ssh -L 8080:www.example.com:80 -L 12345:example.com:80 user@<host-used-as-jump-server> ## bind the 8080 to be accessible only from 127.0.0.1 (local) ssh -L 127.0.0.1:8080:www.example.com:80 -L 12345:example.com:80 user@<host-used-as-jump-server> ## remote ## remote-SSH-server:5900 will be forwarded to localhost:5900 ssh -R 5900:localhost:5900 user@<remote-SSH-server> ## dynamic ## creates a SOCKS tunnel on 1080 ssh -D 1080 user@<remote-SSH-server>
- -C compress
Build and Install¶
make
ritual./configure make && make check sudo make install # or ./configure && make -j2 sudo make install ./configure --prefix=$HOME/abcdefg make make check make install
Libraries
sudo ldconfig # as root echo /usr/local/lib > /etc/ld.so.conf.d/usr_local_lib.conf ldconfig
Strip debug codes
strip xxx
Debugging¶
Debugging Shell Scripts
set -o xtrace sh -x ./script.sh # write "#!/bin/sh -xv" at the beginning of the script
Memory leaks
gdb jdb valgrind
Measure Time
time [command] /usr/bin/time -v [command]
Debuggers
gdb jdb
Popular Paths¶
See What is the exact difference between a ‘terminal’, a ‘shell’, a ‘tty’ and a ‘console’? for difference among pts and tty and so on.
- /dev/pts
- the shells, can be used to message that shell
- /dev/null
- The magical trash bin, or black hole
Also see Linux Root Directory Structure, another page on this website.
Uncanny Commands¶
Sleep
- Sleep for [number] seconds
sleep [number] # print loading... with more and more dots echo -n "loading" while [ '<some-status-checking-cmd> &> /dev/null; echo $?' -ne 0 ] do echo -n "." sleep 2 # sleep for 2 seconds done
Output repeatedly until killed
- May break the shell or ssh connection due to network lag (cannot kill)
yes
Wait
- wait for a job to complete
sleep 8& # get pid of specific process wait `ps -C sleep -o pid=` wait `pidof sleep`
Message¶
Turn on/off
- It’s just turning of/off the write permission of one’s pts file
mesg y mesg n
Send messages
write [pts] wall # write all
Hardware Information¶
Get/Set SATA/IDE device parameters
hdparm
PCI devices
- -v
lspci
USB devices
lsusb -v lsinput
Models loaded in the Linux Kernel
lsmod
CPU
- troubleshoot
cat /proc/cpuinfo
Mem
- troubleshoot
free cat /proc/meminfo
HDD
df -h sudo fdisk -l hdpam -i /dev/sda[ID]
Disk and Filesystem¶
Mount filesystems
mount
Unmount filesystems
umount
Disk management
fdisk
Remount root partition
mount -o remount,rw /
Run levels¶
- runlevel
- init
Power¶
Shutdown and reboot
- -h hold/poweroff the machine
- -r Reboot
- time can be
- now
- +10
- 23:10
shutdown [-h/-r] [time] shutdown -h shutdown -r poweroff # shutdown right now reboot # reboot right now
- Fun fact:
-h
is to display help usually, but if you want help fromshutdown
, it’s shutdown right now!
Printers¶
Command-Line Printing and Options
lpr -P [printer] file1 file2 file3 ...
lpr -P [printer] < file1
lpq -P [printer]
lprm -P [printer] [Jobs-id\username]
Gpg Signature¶
gpg
gpg --import [keyfile]
gpg2 --keyserver [URL_to_key_server] --search-keys [sender]
gpg --verify [sigfile] [file]
gpg --gen-key # generate new key
gpg --full-generate-key # generate new key pair ("full featured")
gpg --gen-revoke [KEYID] # generate revoke
gpg --send-keys [KEYID] # publish your keys to internet
gpg --fingerprint
gpg --list-keys
gpg --list-secret-keys --keyid-format LONG # list private keys
gpg --export
gpg --export -a "some user name" # -a for armored ascii
gpg --export -a "some user name" > public.key # -a for armored ascii
gpg --export-secret-key -a "some user Name" > private.key # export private key
gpg --import private-or-public.key # import key
gpg --delete-key "some user Name"
gpg --delete-secret-key "some user Name"
gpg -e -u "some user name, use this sender's key to encrypt" -r "other user name, use this receiver's public key to decypt" <some-file>
gpg -d <some-file.gpg> > <output-file-name> # redirect to a file
gpg -o <output-file-name> -d <some-file.gpg> # -o must proceed -d
Use gpg
with git
git config --global commit.gpgsign true # turn on gpg sign
git config --global user.signingkey [KEYID] # assign gpg key
# windows gpg
git config --global gpg.program "/c/GnuPG/bin/gpg.exe"
git config --global gpg.program "C:\GnuPG\bin\gpg.exe"
git commit --amend --no-edit -n -S # sign the last commit, maybe need to force push later
git rebase --exec 'git commit --amend --no-edit -n -S' -i [tag,hash] # another way to go?
Also config file available
~/.gnupg/gpg.conf
~/.gnupg/gpg-agent.conf
Distribution Specific¶
Debian¶
Ubuntu is based on Debian
Install build essentials
sudo apt install build-essential sudo aptitude install build-essential
Unattended Upgrades
- “keep the computer current with the latest security (and other) updates automatically”
- at least for the security updates
- not recommend auto-update all packages
- UnattendedUpgrades - Debian Wiki
sudo apt-get install unattended-upgrades apt-listchanges sudo editor /etc/apt/apt.conf.d/50unattended-upgrades
upgrade
upgrade
will potentially hold back versions and cause potential problems
sudo apt-get dist-upgrade # OR sudo apt full-upgrade
Reconfig timezone
sudo dpkg-reconfigure tzdata
List installed packages and search
dpkg-query -l
Add apt source
sudo editor /etc/apt/sources.list.d/newlist.list
Miscellaneous¶
Linux Observability Tools
-
- troubleshoot
- has the prominent chart above
Trick to run redirect using sudo
sudo sh -c 'echo xxx >/xxx/xxx'
Convert all tab to spaces
find . -name '*.java' ! -type d -exec bash -c 'expand -t 4 "$0" > /tmp/e && mv /tmp/e "$0"' {} \;
Download all files from a website
wget -A pdf,jpg -m -p -E -k -K -np <some-url> wget --accept pdf,jpg --mirror --page-requisites --adjust-extension --convert-links --backup-converted --no-parent <some-url>
Calculator
echo "scale=6;(2/3)+(7/8)" | bc
sass auto minify
sass --watch a.scss:a.css --style compressed
Sort based on line length
cat testfile | awk '{ print length, $0 }' | sort -n -s | cut -d" " -f2- cat testfile | awk '{ print length, $0 }' | sort -n | cut -d" " -f2-