Open rogerxu opened 7 years ago
jlevy/the-art-of-command-line: Master the command line, in one page
打造高效的工作环境 – Shell 篇 | 酷 壳 - CoolShell
explainshell.com - match command-line arguments to their help text
What is difference between bash, zsh, tcsh, sh etc.? Which one should I use? - Quora
Unix Shells - csh, ksh, bash, zsh, ...
$ cat /etc/shells
/bin/bash
/bin/csh
/bin/dash
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh
$ chsh -s $(which zsh)
$ echo $SHELL
/bin/zsh
Bash Reference Manual (gnu.org)
Idnan/bash-guide: A guide to learn bash (github.com)
How to Install and Use the Linux Bash Shell on Windows 10
You should use "double quotes" for any argument that contains expansions (such as $variable
or $(command)
expansions) and 'single quotes' for any other arguments. Single quotes make sure that everything in the quotes remains literal, while double quotes still allow some bash syntax such as expansions.
$ rm "/home/$username"
if
then
elif
else
fi
time
until
done
esac
coproc
select
The format of a pipeline is
[time [-p]] [!] command1 [ | or |& command2 ] …
If |&
is used, command1’s standard error, in addition to its standard output, is connected to command2’s standard input through the pipe; it is shorthand for 2>&1 |
. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.
time -p ! rm greeting.txt
A list
is a sequence of one or more pipelines separated by one of the operators ;
, &
, &&
, or ||
, and optionally terminated by one of ;
, &
, or a newline.
rm hello.txt || echo "Couldn't delete file." >&2
循环 - Bash 脚本教程 - 网道 (wangdoc.com)
until
until test-commands; do
consequent-commands;
done
while
while test-commands; do
consequent-commands;
done
for
for name in words;
do
commands;
done
for (( initialisation ; ending-condition ; update ));
do
commands;
done
for x := 1 to 10 do
begin
commands
end
Conditional Constructs (Bash Reference Manual) (gnu.org)
if
if test-commands; then
consequent-commands;
elif more-test-commands; then
more-consequents;
else alternate-consequents;
fi
if ! rm hello.txt; then echo "Couldn't delete file" >&2; exit 1; fi
rm hello.txt || { echo "Couldn't delete file" >&2; exit 1; }
case
case word in
pattern1 | pattern2 ) command-list;;
pattern3 | pattern4 ) command-list;;
*) command-list;;
esac
select
select name in words;
do
commands;
done
((...))
(( expression ))
[[...]]
Return a status of 0 or 1 depending on the evaluation of the conditional expression.
[[ expression ]]
()
( list )
Placing a list of commands between parentheses causes a subshell environment to be created, and each of the commands in list
to be executed in that subshell. Since the list
is executed in a subshell, variable assignments do not remain in effect after the subshell completes.
{}
{ list; }
Placing a list of commands between curly braces causes the list
to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list
is required.
A coprocess
is some more bash syntax sugar: it allows you to easily run a command asynchronously and also set up some new file descriptor plugs that connect directly to the new command's input and output.
coproc NAME command redirections
When the coprocess is executed, the shell creates an array variable named NAME
in the context of the executing shell. The standard output of command
is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[0]
. The standard input of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[1]
. This pipe is established before any redirections specified by the command. The file descriptors can be utilized as arguments to shell commands and redirections using standard word expansions.
coproc auth { tail -n1 -f /var/log/auth.log; }
read latestAuth <&"${auth[0]}"
echo "Latest authentication attempt: $latestAuth"
Bash 函数 - Bash 脚本教程 - 网道 (wangdoc.com)
#!/bin/bash
function say() {
echo $1
}
say "Hi!"
exists() { [[ -x $(type -P "$1" 2>/dev/null) ]]; }
exists gpg || echo "Please install GPG" <&2
The parentheses should always be empty.
name=value
$1
${1}
${10}
Special Parameters - Bash Reference Manual
$*
- Expands to the positional parameters, starting from 1. - "$1 $2..."
$@
- Expands to the positional parameters, starting from 1. - "$1" "$2"
$#
- Expands to the number of positional parameters in decimal.$?
- Expands to the exist status of the most recently executed foreground pipeline$-
- Expands to the current option flags.$$
- Expands to the process ID of the shell.$!
- Expands to the process ID of the job most recently placed into the background.$0
- Expands to the name of the shell or shell script.$ echo a{d,c,b}e
ade ace abe
~
- The value of $HOME
~/foo
- $HOME/foo
~fred/foo
- /home/fred/foo
~+/foo
- $PWD/foo
~-/foo
- ${OLDPWD-'~-'}/foo
~2
- dirs +2
~+2
- dirs +2
~-2
- dirs -2
indirect expansion
$ myvar=USER
$ echo ${!myvar}
rogerxu
${parameter}
${parameter:-word}
- the default value is the expansion of word
${parameter:=word}
- the default value is assigned as the expansion of word
${parameter:?word}
- default output the expansion of word
to the console${parameter:+word}
- if parameter is not empty, replace with the expansion of word
${parameter:offset}
- Substring Expansion. The substring of the value starting at the offset
and extending to the end of the value.${parameter:offset:length}
${parameter: -offset:length}
- A negative offset must be separated from the colon by at least one space to avoid being confused with the :-
expansion.${#parameter}
- The length of parameter
${parameter#word}
- Remove the beginning of the value for the matched pattern${parameter##word}
- Remove the beginning of the value for the matched pattern${parameter%word}
- Remove the end of the value for the matched pattern${parameter%%word}
- Remove the end of the value for the matched pattern${parameter/pattern/string}
- Replace the matched pattern (e.g., begins with #
or %
) with string
${parameter@operator}
U
- convert to uppercaseu
- first character convert to uppercaseL
- convert to lowercaseQ
- quotedE
- backslash escape P
- prompt stringA
- recreate parameter with its attributes and valueK
- quoted version of the valuea
- flag values representing parameter's attributes$(command)
`command`
$(( expression ))
<(list)
>(list)
*
?
[...]
Input Output & Error Redirection in Linux [Beginner's Guide]
stdin
) is the source of input data. By default, stdin
is any text entered from the keyboard. It’s stream ID is 0.stdout
) is the outcome of command. By default, it is displayed on the screen. It’s stream ID is 1.stderr
) is the error message (if any) produced by the commands. By default, stderr
is also displayed on the screen. It’s stream ID is 2.Redirecting Input
<file
Read line from "file.txt" to FD 0.
$ read line <file.txt
Redirecting Output
>file
Redirect FD 1 to the file "myfile.txt" and FD 2 to the file "/dev/null".
$ ls -l a b >myfile.txt 2>/dev/null
Appending Redirected Output
>>file
Append to "file.txt"
$ echo hello >>file.txt
Redirecting Standard Output and Standard Error
&>file
Duplicate file descriptors. Make FD 2 write to where FD 1 is writing.
$ ls -l a b >myfile.txt 2>&1
$ ls -l a b &>myfile.txt
Appending Standard Output and Standard Error
&>>file
$ ls -l a b &>>myfile.txt
<<delimiter
here-document
delimiter
Make FD 0 (standard input) read from the string between the delimiters.
cat <<.We choose . as the end delimiter.
Hello world.
Since I started learning bash, you suddenly seem so much bigger than you were before.
.
Remove leading tab characters
<<-delimiter
here-document
delimiter
<<< string
Make FD 0 (standard input) read from the string.
$ cat <<< "Hello
World"
Hello
World
Copy FD y to FD x
x<&y
x>&y
Close FD x
x<&-
x>&-
Duplicate FD 1 to FD 3
exec 3>&1 >mylog; echo moo; exec 1>&3 3>&-
Move FD y to FD x and close FD y.
x<&y-
x>&y-
Replace FD x
with FD y
.
exec 3>&1- >mylog; echo moo; exec >&3-
n<>file
Bash 脚本入门 - Bash 脚本教程 - 网道 (wangdoc.com)
Minimal safe Bash script template | Better Dev
#!/usr/bin/env bash
cd
exec
export
pwd
test
umask
unset
alias
command
$ command -V z
z is an alias for _z 2>&1
declare
echo
help
printf
source
source filename
type
You can find out whether a command is an executable, shell builtin or an alias by using type
command.
$ type ls
ls is an alias for ls --color=tty
$ type cd
cd is a shell builtin
$ type cat
cat is /bin/cat
unalias
set
The Set Builtin (Bash Reference Manual) (gnu.org)
set
allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables.
Display the names and values of all shell variables and functions.
set
Set shell attributes
set -o option-name
Print shell input lines as they are read.
set -v
set -o verbose
Export each variable or function.
set -a
set -o allexport
Exit if unset variables
set -u
set -o nounset
Exit immediately if a pipeline returns a non-zero status.
set -e
set -o errexit
Print a trace of commands before they are executed.
set -x
set -o xtrace
Read commands but do not execute them. It is used to check a script for syntax errors.
set -n
set -o noexec
shopt
The Shopt Builtin (Bash Reference Manual) (gnu.org)
shopt
allows you to change additional shell ooptioal behavior.
HOME
IFS
PATH
PS1
- The primary prompt string. The default value is "\s-\v\$
".PS2
- The secondary prompt string. The default value is ">
".ENV
HOSTNAME
LANG
LC_ALL
PS0
PS4
- When the -x
option is set, printed before the command line. The default value is "+
".PWD
RANDOM
- Random integer between 0 and 32767.SHELL
SHELLOPTS
TMPDIR
UID
Bash Conditional Expressions (Bash Reference Manual) (gnu.org)
Conditional expressions are used by the [[
compound command and the test
and [
builtin commands. The test
and [
commands determine their behavior based on the number of arguments; see the descriptions of those commands for any other command-specific actions.
When used with [[
, the ‘<’ and ‘>’ operators sort lexicographically using the current locale. The test command uses ASCII ordering.
string
-n
string - True if the length of string is non-zero.-z
string - True if the length of string is zero.file
-a
file - True if file exists.-d
file - True if file exists and is a directory.-e
file - True if file exists.-f
file - True if file exists and is a regular file.-r
file - True if file exists and is readable.-s
file - True if file exists and has a size greater than zero.-x
file - True if file exists and has execute permission.数组 - Bash 脚本教程 - 网道 (wangdoc.com)
Declare an array
declare -a name
Declare an associative array
declare -A name
Assign array
name=(value1 value2 value3)
Read one member
${array[i]}
Read all members
${array[@]}
$ names=( foo "hello world" bar )
$ for name in "${names[@]}"; do echo "$name"; done
foo
hello world
bar
Read default value (0)
${array}
is same as ${array[0]}
Length
${#array[@]}
Slice
${array[@]:position:length}
Delete member
unset array[i]
Clear
unset array
Directory Stack Builtins (Bash Reference Manual) (gnu.org)
目录堆栈 - Bash 脚本教程 - 网道 (wangdoc.com)
dirs
popd
pushd
Bash 启动环境 - Bash 脚本教程 - 网道 (wangdoc.com)
Controlling the Prompt (Bash Reference Manual) (gnu.org)
命令提示符 - Bash 脚本教程 - 网道 (wangdoc.com)
PROMPT_COMMAND
8 Command Line Editing - Bash Reference Manual
Bash 行操作 - Bash 脚本教程 - 网道 (wangdoc.com)
Shortcuts to move faster in Bash command line - teohm
Bash Reference Manual: Commands For Completion
PATH
$ type echo
echo is a shell builtin
echo is /usr/bin/echo
echo is /bin/echo
Bash only performs a PATH
search on command names that do not contain a /
character. Command names with a slash are always considered direct pathnames to the program to execute.
$ sudo apt install zsh
$ zsh --version
git
$ sudo apt install git
$ git --version
wget
sh -c "$(wget -O - https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
curl
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
Append the following instruction to hide the terminal context.
.zshrc
path=(~/.cargo/bin $path)
prompt_context(){}
ZSH_THEME="agnoster"
romkatv/powerlevel10k: A Zsh theme (github.com)
ZSH_THEME="powerlevel10k/powerlevel10k"
$ p10k configure
.p10k.zsh
Fix for Visual Studio Code Shell Integration
.zshrc
if [[ "$TERM_PROGRAM" == "vscode" ]]; then
ITERM_SHELL_INTEGRATION_INSTALLED="Yes"
fi
# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh.
[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh
MacOS X + oh my zsh + powerline fonts + visual studio code terminal settings (github.com)
brew tap homebrew/cask-fonts
Nerd Fonts - Iconic font aggregator, glyphs/icons collection, & fonts patcher
brew install --cask font-hack-nerd-font
brew install --cask font-meslo-lg-nerd-font
brew install --cask font-fira-code-nerd-font
Cheatsheet · ohmyzsh/ohmyzsh Wiki
$ alias -L
gb
- git branch
gba
- git branch -a
gbd
- git branch -d
gbnm
- git branch --no-merged
gbr
- git branch --remote
gco
- git checkout
gcb
- git checkout -b
gcm
- git checkout master
gcount
- git shortlog -sn
gfa
- git fetch --all --prune
gl
- git pull
glol
- git log --graph --pretty=...
glola
- git log --graph --pretty=... --all
gst
- git status
gp
- git push
gpsup
- git push --set-upstream origin $(current_branch)
alias l="exa --icons"
alias l1="exa -1 --icons"
alias la="exa -1a --icons"
alias ll="exa -l --icons"
alias lla="exa -la --icons"
alias tree="exa -Ta -L=1 --icons"
alias lt="tree"
.zshrc
plugins=(
git
aliases
colored-man-pages
colorize
command-not-found
cp
themes
z
#zoxide
zsh-autosuggestions
zsh-syntax-highlighting
)
zsh-users/zsh-autosuggestions: Fish-like autosuggestions for zsh (github.com)
Clone this repository into $ZSH_CUSTOM/plugins
(by default ~/.oh-my-zsh/custom/plugins
)
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
zsh-users/zsh-syntax-highlighting: Fish shell like syntax highlighting for Zsh. (github.com)
git clone https://github.com/zsh-users/zsh-syntax-highlighting ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
zsh-users/zsh-completions: Additional completion definitions for Zsh. (github.com)
git clone https://github.com/zsh-users/zsh-completions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-completions
.zshrc
# zsh-completions
fpath+=${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-completions/src
source $ZSH/oh-my-zsh.sh
$ acs <query>
$ sudo apt install python3-pygments
$ which pygmentize
/usr/bin/pygmentize
Usage
ccat .zshrc
cless .zshrc
$ lstheme
$ theme <theme>
https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/z
$ z -l
简介 - PowerShell | Microsoft Docs
$ $PSVersionTable
Name Value
---- -----
PSVersion 7.1.3
PSEdition Core
GitCommitId 7.1.3
OS Microsoft Windows 10.0.18363
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
$ echo $PROFILE
C:\Users\<username>\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
$ New-Item $PROFILE
Execution Policy
$ Get-ExecutionPolicy
Restricted
$ Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
$ Get-ExecutionPolicy
RemoteSigned
$ $env:HTTPS_PROXY="http://127.0.0.1:7890"
Install from non-admin PowerShell in C:\Users\<YOURUSERNAME>\scoop
.
iwr -useb get.scoop.sh | iex
Run in non-admin PowerShell
scoop bucket add nerd-fonts
Run in admin PowerShell
sudo scoop install -g cascadiacode-nf
Install-Module oh-my-posh -Scope CurrentUser
Edit $PROFILE
# oh-my-posh
Set-PoshPrompt -Theme powerlevel10k_rainbow
Basic Line Editing Tricks and Shortcuts for Windows PowerShell
Left
- move back one characterRight
- move forward one characterDel
- delete current characterBackspace
- delete backward character Ctrl-Left
- move back one wordCtrl-Right
- move forward one wordCtrl-Del
- delete to the end of the current wordCtrl-Backspace
- delete to the start of the current wordHome
- move to the start of the lineEnd
- move to the end of the lineCtrl-Home
- delete to the start of the lineCtrl-End
- delete to the end of the lineRight-click
- pasteGet-Command
- which
$ Get-Command -All where
CommandType Name Version Source
----------- ---- ------- ------
Alias where -> Where-Object
Application where.exe 10.0.1904… C:\Windows\system32\where.exe
How To Read and Set Environmental and Shell Variables on a Linux VPS | DigitalOcean
We can see a list of all of our environmental variables by using the env
or printenv
commands. In their default state, they should function exactly the same:
$ env
$ printenv
with printenv
, you can requests the values of individual variables:
$ printenv HTTPS_PROXY
http://127.0.0.1:8088
env
let's you modify the environment that programs run in by passing a set of variable definitions into a command like this:
$ env VAR1="blahblah" command_to_run command_options
List variables
$ set
Set variable
$ TEST_VAR='Hello World!'
Get variable
$ set TEST_VAR
Hello World!
Delete variable
$ unset TEST_VAR
Export shell variable to an environmental variable
$ export HTTPS_PROXY=http://127.0.0.1:8088
$ printenv HTTPS_PROXY
HowTo: Set an Environment Variable in Windows - Command Line and Registry - Dowd and Associates
Set - Environment Variable - Windows CMD - SS64.com
List all environment variables
$ set
Display a variable
$ echo %HTTP_PROXY%
http://127.0.0.1:8088
$ set HTTP_PROXY
http://127.0.0.1:8088
$ set http
HTTP_PROXY=http://127.0.0.1:8088
HTTPS_PROXY=http://127.0.0.1:8083
Set a variable
There is no need to add quotation marks when assigning a value that includes spaces
$ set TEST_VAR=one two three
If you place quotation marks around the value, then those quotes will be stored:
$ set TEST_VAR="one & two"
Delete a variable
$ set TEST_VAR=
Better still, to be sure there is no trailing space after the = place the expression in parentheses or quotes:
$ (set TEST_VAR=)
or
$ set "TEST_VAR="
about_Environment_Variables | Microsoft Docs
List all environment variables
$ Get-ChildItem Env:
Display environment variable
$ echo $Env:HTTP_PROXY
http://127.0.0.1:8088
$ Get-Childitem Env:HTTP_PROXY
Set environment variable
$ $Env:HTTP_PROXY = "http://127.0.0.1:8088"
Delete environment variable
$ Remove-Item Env:HTTP_PROXY
apt install batcat
apk add bat
$ bat file
apt install exa
$ exa --icons
$ exa -1 --icons
$ exa -1a --icons
$ exa -l --icons
$ exa -Ta -L=1 --icons
lsd
delta
$ sudo apt install delta
duf
muesli/duf: Disk Usage/Free Utility - a better 'df' alternative (github.com)
$ brew install duf
dust
bootandy/dust: A more intuitive version of du in rust (github.com)
apk add dust
$ dust -r -d 1 dir
ncdu
NCurses Disk Usage (yorhel.nl)
apk add ncdu
apt install ncdu
broot
$ sudo apt install broot
$ broot
$ sudo apt install ripgrep
$ rg 'regexp' file
fd
sharkdp/fd: A simple, fast and user-friendly alternative to 'find' (github.com)
$ sudo apt install fd-find
$ fd pattern
fzf
junegunn/fzf: A command-line fuzzy finder (github.com)
$ sudo apt install fzf
$ fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}'
ag
mcfly
choose
sd
$ sudo apt install sd
$ sd before after
jq
cheat
tldr
tldr | simplified, community driven man pages (ostera.io)
tealdeer
dbrgn/tealdeer: A very fast implementation of tldr in Rust. (github.com)
apt install tealdeer
brew install tealdeer
$ tldr --update
$ tldr --list
$ tldr tar
navi
denisidoro/navi: An interactive cheatsheet tool for the command-line (github.com)
apk add navi
brew install navi
bottom
ClementTsang/bottom: Yet another cross-platform graphical process/system monitor. (github.com)
$ cargo install bottom
$ brew install bottom
$ btm
glances
Glances - An Eye on your system (nicolargo.github.io)
$ pip install glances
$ sudo apt install glances
gtop
aksakalli/gtop: System monitoring dashboard for terminal (github.com)
$ npm i -g gtop
zenith
$ brew install zenith
prettyping
brew install prettyping
$ prettyping bing.com
gping
brew install gping
$ gping bing.com
procs
dalance/procs: A modern replacement for ps written in Rust (github.com)
$ cargo install procs
$ brew install procs
$ procs zsh
$ wget -O config.yaml https://example.com/file
curl 的用法指南 - 阮一峰的网络日志 (ruanyifeng.com)
$ curl -o example.html https://www.example.com
httpie
curlie
xh
brew install zoxide
$ zoxide query -ls
$ z foo
dog
nnn
$ brew install nnn
Usage · jarun/nnn Wiki (github.com)
gitui
extrawurst/gitui: Blazing 💥 fast terminal-ui for git written in rust 🦀 (github.com)
$ cargo install gitui
$ brew install gitui
tig
Introduction · Tig - Text-mode interface for Git (jonas.github.io)
$ sudo apt install tig
$ brew install tig
macchina
$ cargo install macchina
$ brew install macchina
AWK Tutorial: 25 Practical Examples of AWK Command in Linux (linuxhandbook.com)
awk 入门教程 - 阮一峰的网络日志 (ruanyifeng.com)
Understanding AWK - Earthly Blog
$ awk 'condition action' file
$ awk BEGIN { before all }
$ awk END { after all }
$0
- line$1
- first fieldNF
- number of fields$NF
- last field$(NF-1)
- last -1 field$NR
- row number~ /pattern/
- pattern condition$ awk '{print $0}' demo.txt
$ awk '{print $1}' demo.txt
$ awk '{print $(NF-1)}' demo.txt
-F '\t'
List all users
$ awk -F ':' '{print $1}' /etc/passwd
root
daemon
toupper()
tolower()
length()
substr()
$ awk '$1 ~ /pattern/ {print $0}' demo.txt
$ awk -F ':' 'NR > 3 {print $1}' demo.txt
$ awk -F ':' '{if ($1 > "m") print $1; else print "---"}' demo.txt
Getting Started With SED Command Beginner’s Guide (linuxhandbook.com)
$ sed -i 's/source/target/g' demo.txt
sd
$ echo 'find something' | sd 'find' 'replace'
# plain string
$ echo 'remove (<>) special chars' | sd -s '(<>)' ''
$ sd 'find' 'replace' file.txt
How to find a domain's authoritative nameservers (jvns.ca)
$ dig +short ns ppy-moble.0098dns02in.work
$ dig @h.root-servers.net ppy-moble.0098dns02in.work
$ dig @a.nic.work ppy-moble.0098dns02in.work
$ dig @vip7.alidns.com ppy-moble.0098dns02in.work
Tmux 使用教程 - 阮一峰的网络日志 (ruanyifeng.com)
Gentle Guide to Get Started With tmux | Pragmatic Pineapple 🍍
$ tmux
Prefix key: Ctrl
-b
Ctrl-b
- ?
- list shortcuts