文档章节

learn bash

好铁
 好铁
发布于 2014/05/23 20:36
字数 1781
阅读 257
收藏 3
点赞 0
评论 0
/etc/profile => /etc/bash.bashrc => ~/.profile => ~/.bashrc

force_color_prompt=yes   

${EDITOR:-emacs}  #if varialbe $EDITOR exist, use it; otherwise set the default value as "emacs"

less -X          #do not refresh the screen after less

/bin/rm or \rm       #full path or '\' can escape the alias

HISTSIZE         #the count of commands in history file
HISTFILESIZE       #maxmium size of histfile
HISTIGNORE      #commands in the list will not be recorded
HISTCONTROL      #ignore lead space, reduplicative commands
HISTTIMEFORMAT      #save time stamp in history. strftime(3)
/etc/inputrc      #for shell which uses readline (bash,dash,zsh)

/etc/wgetrc,~/.wgetrc  #set proxy fot wget

VARIABLE

assignment: 1. VAR=value    2. read VAR        3. VAR=`date`, VAR=$(date)
$0        command self
$#        arguments counts
$*        all parameters, list be treated as whole one
$@        all parameters, list be treated as every one
$?        return code of last command
$!        process ID
$$        shell's pid, usually used to create tempfile as name
shift        remove variables

$PIPESTATUS        last pipe return value
$SECONDS       shell's run time,add 1 per second.in script, it is script's time
$RANDOM           ramdom number
$BASHOPTS       shopt list,same as 'shopt|grep -w on', 'shopt -s' to turn on, '-u' to turn off
           checkwinsize -- update LINES and COLUMNS
           cmdhist    -- compress command to one line in history
           hostcomplete -- complete command expand to hostname, act on /etc/hosts
$SHELLOPTS       list of 'shopt -o'
           'set -o' or '-e' to  turn on, '+o' '+e' to turn off
           errexit     -- if command return not zero value, shell will exit
           noglob    -- pathname expand
           monitor    -- backgroud cmd finished, bash show a message before next prompt
           pipefail    -- substitute PIPESTATUS
           '-x'        -- when run a cmd, show it first, useful for debug (#!/bin/sh -x)
$BASH_COMMAND       current execute cmd name
$BASH_SOURCE       current file
$BASH_LINENO       script current line number
$FUNCNAME       current function name
           FUNCNAME[0]  -- current func
           FUNCNAME[1]  -- upper func
$HOSTNAME       uname -n(more reliable, and can not be modificated by user)
$HOSTTYPE       uname -m
$PWD, $OLDPWD       pwd, cd -
$TIMEFORMAT       'time' command output format,%U represent user, %S system, %R total
$PPID           parent shell's pid
$RANDOM           random number 0~32767
$REPLY           'read' command's default variable
$BASH_XTRACEFD       '-x' option, define output to which file(default stderr)
$GLOBIGNORE       ingore wildchar pattern. GLOBIGNORE=*~(ignore backup file)
$IFS           internal field separator:list the char used for space(defau:space,tab,newline)
$PATH           '.' and '::' represent current dir,in PATH, the ":" on head or tail position will extend as current dir
$TMOUT           act on 'read' 'select' or interaction shell, TMOUT seconds timeout
$TMPDIR           default is /tmp
$GROUPS        group id

${var}iable       # usually, if include constant, string, filename, use uppercase; number, input, use lowercase
$((..)) ,  expr       # math calculation, string instead by 0
${#variable}       # variable's length
${parameter:offset[:length]}    #cut string
${parameter: -offset[:length]}    #cut from tail
${variable#word}          #from head, not greedy matching
${variable##word}        #greedy match, as long as possible
${variable%word}        #from tail, not greedy
${var%%word}            #greedy
${variable/old/new}        #replace one
${variable//old/new}        #replace all
${var/#old/new}            #start with old
${var/%old/new}            #end with old
${var/pattern}            #pattern remove
${variable^^}            #transpose to uppercase
${var,,}            #to lowercase
${parameter:-word}        # provide default value
${param:=word}            # set default value for variable
${var?message}            # if not be assigned, show message
${var+foo}            # if has a value, foo will be calculated, if not return empty string
${!var}                #use a var's name to visit another's value



WILDCHILD

[[:graph:]]       A-Z,a-z,0-9 and punctuation
[[:alpha:]]       A-Z,a-z
...
! and ^ at the head stand for don't include

set -o noglob (set -f)      toggle off globbing('+' to toggle on)
shopt -s dotglob   '*' matches dotfiles
shopt -s nullglob  glob as null
           failglob  if not match, throw shell error instead deal with it
shopt -s extglob   #
                  ?(pattern), +(pattern), @(pattern)--match one ,!(pattern)--exclude,*()
shopt -s nocaseglob           ignore case

CONDITION
[ is a program, ']' just the guy's parameter
-a -e          # whether exist
-f         # regular file
-b        # block device
-c        # character device
-L -h        # symbolic link
-S         # socket
-p        # pipe
-d        # directory
-r -w -x    # permission
-O            # owned by the effective uid
-G        # gid
-g        # suid
-u        # sgid
-z        # if length zero, true
-n        # not zero, true
-s         # exist and greater than zero
-N        # last read, whether modified
A -ef B        # if same inode of hard link
  -nt         # new than -- mtime
  -ot        # old than
  =         # same string
[[ "s1" < "s2" ]] #
[ != ]                 # not same
[[ =~ ]]      # regex test. BASH_REMATCH[] contain matched expression
[ -eq ]          # number equal
  -ne           # not equal
  -lt          # less than
  -gt          # greater than
  -ge -le      # not less, not greater

case statement
;;&    #go match follow all pattern
;&    #follow one pattern has been matched

LOOP
for foo in $var #has been  know same opetation on a set, not until satisfied a condition,
               ('in $var' selectable, treated as $@

while        #suitable for there is no list needed to traverse and need a condition to end the loop
        #such as math, time compare, current process's outside status, continuing show option and read
              user's input

: true        # always true, return 0

read -n1 -p    # read one char, show prompt
break n , continue n

select          # execute loop, show prompt, set var to provided value, assign $REPLY with user input
          useful for build simple menu quickly

FUNCTION and LIBRARY
func(), function foo, function foo()    # three form, the first is universal
tail -F         #output appended data as the file grows
pidof         #find the pid of the named prog
trap         #catch dignal
local         #define local variable

/etc/security/limits.conf      # nofile , maximum of open file

$OPTARG             #option list
$OPTIND         #index of current option

ARRAY
array=(foo bar baz qux)
read -a        #read element to array
IFS=: read ..    #only affect read
${#array[@]} or ${#array[*]}   #the counts of array elements
${array[@]:m:n}               #substr, from position m, forward n elements
declare -A array           #relative array
${!array[@]}               #reverse referance
+=                   #append elements
unset                   #delete elements

PROCESS
ps -fp<pid>
   -ft<terminal>
   -fu<user>
   -F    #more details
   -eaf    #all process
grep -w foobar | grep -v grep <=> grep -w foo[b]ar <=> pgrep
pgrep -l foo   #pid and name
      -u user
      -x exact
      -d    #IFS
pidof foo    #find by id, pgrep find by binary file name
/proc/self     #running process
/proc/$$    #shell's pid

exec wait nohup

SHELL FAMILY
ksh
    mksh, ksh93
csh
    like C, ~,
tcsh
    pushd,popd, locktty, correct spell,
zsh
    more powerful
dash
    small, quick

su -  #login shell
su    #not login, only interactive shell
---------------------------------------------------------
interactive login shell
bash        # /etc/profile => ~/.bash_profile, ~/.bash_login, ~/.profile(as find first as read)
csh        # /etc/csh.cshrc => /etc/csh.login, /etc/.login, /etc/login.std, /etc/cshrc(depend specify OS) => ~/.cshrc,
          ~/.login
sh        # /etc/profile => ~/.frofile
tcsh        # same as csh, if ~/.tcshrc exist, replace ~/.cshrc
ksh        # /etc/profile => ~/.profile => /etc/ksh.kshrc => ~/.kshrc
zsh         # /etc/zsh/zshenv => $ZDOTDIR/.zshenv => /etc/zsh/zprofile => $ZDOTDIR/.zprofile => /etc/zshrc =>
          $ZDOTDIR/zshrc => /etc/zsh/slogin => $ZDOTDIR/.zlogin

---------------------------------------------------------
interactive nologin shell
bash        # ~/.bashrc
csh        # /etc/csh.cshrc, ~/.cshrc
sh        # if $ENV, read it, else nothing
tcsh        # /etc/csh.cshrc => ~/.tcshrc , ~/.cshrc
ksh        # /etc/ksh.kshrc => ~/.kshrc
zsh        # /etc/zsh/zhsenv => $ZDOTDIR/.zshenv =>/etc/zshrc , $ZDOTDIR/.zshrc

---------------------------------------------------------
non-interactive shell
bash        # if $BASH_ENV,read it; else same as sh
csh        # /etc/csh.cshrc => ~/.cshrc
sh        # nothing
tcsh        # /etc/csh.cshrc => ~/.tcshrc, ~/.cshrc
ksh        #nothing
zsh        # /etc/zsh/zshenv => $ZDOTDIR/.zshenv

---------------------------------------------------------
logout shell
zsh         # $ZDOTDIR/.zlogout , /etc/zsh/zlogout
bash        # ~/.bash_logout , /etc/bash_logout
csh        # ~/.logout, /etc/.logout , /etc/logout, /etc/csh.logout


FILE OPERATION
stat -c, --format   #"%a %U %G %n"
cat  -n     #line number
     -s     #suppress repeated empty output lines
     -b  #number nonempty lines
     -v     #show nonprinting
     -T  #display TAB as ^I
     -e     #display $ at end of each line
tac       #concatenate and print files in reverse

/dev/zero          # read from most fast
/dev/null          # write in most fast
/dev/urandom          # read from slowly like a snail

echo 3 > /proc/sys/vm/drop_caches    # clear the system cache

mktemp --suffix .txt   

join   #join lines of two files on a common field
       -jFIELD
sort -kFIELD

grep -i    #ingore case
     -w    #match word
     -v    #reverse, list unmatched lines
     -e #multiple pattern
     -l #list file name
     -A    #after context
     -B #before context
     -C #context
split    -b    #specify size
    -d     #numberic
    -a    #suffix length
tee    -a    #append
touch     -d    #date format
find        # use locate can be more fast, need run updatedb
    -exec     #run command


echo     -e     #backslash is special
    -n     #turn off append \n
    ^M     #return
    ^H     #/-\|
fmt    -u    #one space between two words, two space after .
    -pSTR    #reform prefix with STR
    -s    #split long line, if no this, the short line will be join
    -t    #indent first line diffirent with second line
    -w     #maxmium width, default 75
tail     -f    #output appended data as file grows
    -F    # -f --retry
    -n0    #not report the existed content
od    -a    #named char
    -x    #hexdadecimal
    -t    #format type
paste    -d    #delimiter, -d, use csv form
    -s    #serial, paste one file at a time, transform column data to row data
pr    -t    #ignore title
    -T    #ignore page number
    -COL    #column
    -J     #join line, thiner
shuf    -i    # --input-range
    -h     # output at most count lines
    --random-source     #get random bytes from file
sort    -u      #delete repeated
    -c     #only check weather sorted
    -t     #specify separator instead of blank
    -s    #stabilize sort
    -b    #ignore leading blanks
    -d    #dictionary order, ignore punctuation
    -f    #ignore case
    -g    #general numberic sort
    -i    #ignore nonprinting
    -h    #human readable numbers(e.g.,2K 1G)
    -M    #month sort
    -n    #numberic sort
    -R    #sort by random hash of keys
    -r    #reverse the result of comparisons
    -k    #sort via a key

    count the char of strings:echo one number line follow the string
    
tr    -d    #delete
uniq    -u    #only print unique lines
    -d    #only print duplicate lines
    -w    #compare no more than N characters in lines
    -s N    #skip chars
    -f     #skip fields
    -i    #ignore case
    -c    #count
wc    -c    #bytes
    -w    #words
    -l    #lines
getent        #get entries from Name Service Switch libraries
groups        #display current group name

logger        #shell interface to syslog(3)
md5sum    --check    #read MD5 sums from the files
mkfifo        #create named pipes

netcat    -v
    -z
    -l
    -p
    -q
    recipient
pv    -t
    -b

arp    -a
ping    -w    #deadline
    -c     #count
    -b    #broadcast
scp    -B    #batch mode

ssh-keygen    #authentication key generation
ssh-copy-id    #append the public key to remote ~/.ssh/authorized_keys and set permission
        -i    #identity_file
ssh-agent    #auth agent. if not GUI, eval `ssh-agent` will analyse the needed setting.
ssh-add        #adds private key identities to the auth agent
ssh    -n    #redirect stdin from /dev/null(prevent reading from stdin)
    -o    #option. see also ssh_config

openssl        #OpenSSL command line tool
    genrsa    #generation of DSA Private Key from param
    req    #PKCS#10 X.509 Certificate Signing Request Management
s_client    #SSL/TLS client program
s_server    #SSL/TLS server program

nohup        #run a command immune to hangups

seq        
sleep
timeout   -s    #signal
      -k    #send a SIGKILL

uname          #kernel base name
      -n    #hostname
      -r    #kernel realease
      -m    #cpu architecture
      -o    #os
      -i    #hardware plateform

uuencode

xargs    -0    #Input items are terminated by a null character
    -L    #max-lines
    -I    #filename replace str
yes
ps -o comm    #header and process name
   -o comm=    #no header

© 著作权归作者所有

共有 人打赏支持
好铁
粉丝 34
博文 264
码字总数 78066
作品 0
朝阳
程序员
Azure Cloud Shell - your own bash shell and contai

Azure Cloud Shell - your own bash shell and contai Scott Hanselman's Blog2017-12-031 阅读 shellbashcloud Visual Studio Code has a HUGE extension library . There's also almost t......

Scott Hanselman's Blog ⋅ 2017/12/03 ⋅ 0

几步搭建基于Docker的Tomcat运行环境!

Docker旨在提供一种应用程序的自动化部署解决方案,在 Linux 系统上迅速创建一个容器(轻量级虚拟机)并部署和运行应用程序,并通过配置文件可以轻松实现应用程序的自动化安装、部署和升级,非...

技术小能手 ⋅ 06/08 ⋅ 0

国外程序员推荐的免费编程书籍资源

StackOverflow 上有位网友(xenoterracide)提问: 我正试着搜集整理一个可在网上免费阅读的计算机编程书籍列表。这些书可以是某种特定编程语言,也可以计算机方面通用书籍。网上有哪些免费可...

职通网 ⋅ 2011/11/07 ⋅ 1

Mac 常用命令

mysql 问题及解决 修改完mysql的字符集后,之前发生字符集错误的数据库需要重新导入(可以修改数据库的字符集或 备份删库重建再导入),因为数据库内的字符集并非utf8字符集格式,因此以utf...

小小的长大 ⋅ 2016/12/18 ⋅ 2

How to download embedded videos with F12 Tools in

How to download embedded videos with F12 Tools in Scott Hanselman's Blog2017-11-291 阅读 Tools I got an email this week asking how to download some of my Azure Friday video podc......

Scott Hanselman's Blog ⋅ 2017/11/29 ⋅ 0

视频版 |《老运维带你用 Golang 飞》

Outline What is Golang Syntax Concurrent Example Docker Useful tools History Design began in late 2007 by Google. Authors: Rob Pike (Bell Lab & UTF-8) Ken Thompson (UNIX & C & T......

xjtuhit ⋅ 2017/09/22 ⋅ 0

为什么说 Python 是数据科学的发动机(一)发展历程(附视频中字)

毋庸置疑,Python是用于数据分析的最佳编程语言,因为它的库在存储、操作和获取数据方面有出众的能力。 在PyData Seattle 2017中,Jake Vanderplas介绍了Python的发展历程以及最新动态。在这...

Data Analyst ⋅ 2017/10/20 ⋅ 0

nodejs 基础 + http

CRUD应用:创建、读取、更新、删除 AngularJS双向数据绑定 your name:<input type="text" ng-model="yourname" placeholder="world"> hello {{yourname || 'world'}}! AngularJS应用三个组成......

GZhiDao ⋅ 2015/12/10 ⋅ 0

如何在 Windows 10 上开启 WSL 之旅

WSL 可以让你访问 Windows 上的 Linux Bash shell。 在 上一篇文章 中,我们讨论过关于 Windows 的子系统 LinuxWindows Subsystem for Linux(WSL)的目标用户。本文,我们将在 Windows 10 的...

作者: Swapnil Bhartiya ⋅ 04/15 ⋅ 0

如何在 Windows 10 上开启 Linux子系统

WSL 可以让你访问 Windows 上的 Linux Bash shell,在 上一篇文章 中,我们讨论过关于 Windows 的子系统 LinuxWindows Subsystem for Linux(WSL)的目标用户,本文,我们将在 Windows 10 的...

问题终结者 ⋅ 04/23 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

从零开始搭建Risc-v Rocket环境---(1)

为了搭建Rocke环境,我买了一个2T的移动硬盘,安装的ubuntu-16.04 LTS版。没有java8,gcc是5.4.0 joe@joe-Inspiron-7460:~$ java -version程序 'java' 已包含在下列软件包中: * default-...

whoisliang ⋅ 17分钟前 ⋅ 0

大数据学习路线(自己制定的,从零开始学习大数据)

大数据已经火了很久了,一直想了解它学习它结果没时间,过年后终于有时间了,了解了一些资料,结合我自己的情况,初步整理了一个学习路线,有问题的希望大神指点。 学习路线 Linux(shell,高并...

董黎明 ⋅ 23分钟前 ⋅ 0

systemd编写服务

一、开机启动 对于那些支持 Systemd 的软件,安装的时候,会自动在/usr/lib/systemd/system目录添加一个配置文件。 如果你想让该软件开机启动,就执行下面的命令(以httpd.service为例)。 ...

勇敢的飞石 ⋅ 25分钟前 ⋅ 0

mysql 基本sql

CREATE TABLE `BBB_build_info` ( `community_id` varchar(50) NOT NULL COMMENT '小区ID', `layer` int(11) NOT NULL COMMENT '地址层数', `id` int(11) NOT NULL COMMENT '地址id', `full_......

zaolonglei ⋅ 34分钟前 ⋅ 0

安装chrome的vue插件

参看文档:https://www.cnblogs.com/yulingjia/p/7904138.html

xiaoge2016 ⋅ 37分钟前 ⋅ 0

用SQL命令查看Mysql数据库大小

要想知道每个数据库的大小的话,步骤如下: 1、进入information_schema 数据库(存放了其他的数据库的信息) use information_schema; 2、查询所有数据的大小: select concat(round(sum(da...

源哥L ⋅ 59分钟前 ⋅ 0

两个小实验简单介绍@Scope("prototype")

实验一 首先有如下代码(其中@RestController的作用相当于@Controller+@Responsebody,可忽略) @RestController//@Scope("prototype")public class TestController { @RequestMap...

kalnkaya ⋅ 今天 ⋅ 0

php-fpm的pool&php-fpm慢执行日志&open_basedir&php-fpm进程管理

12.21 php-fpm的pool pool是PHP-fpm的资源池,如果多个站点共用一个pool,则可能造成资源池中的资源耗尽,最终访问网站时出现502。 为了解决上述问题,我们可以配置多个pool,不同的站点使用...

影夜Linux ⋅ 今天 ⋅ 0

微服务 WildFly Swarm 管理

Expose Application Metrics and Information 要公开关于我们的微服务的有用信息,我们需要做的就是将监视器模块添加到我们的pom.xml中: 这将使在管理和监视功能得到实现。从监控角度来看,...

woshixin ⋅ 今天 ⋅ 0

java连接 mongo伪集群部署遇到的坑

部署mongo伪集群 #创建mongo数据存放文件地址mkdir -p /usr/local/config1/datamkdir -p /usr/local/config2/data mkdir -p /usr/local/config3/data mkdir -p /usr/local/config1/l......

努力爬坑人 ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部