美文网首页
shell cheatsheet

shell cheatsheet

作者: 右中 | 来源:发表于2018-11-28 19:08 被阅读0次

    源自:https://devhints.io/bash
    此网站的其他内容也不错,例如https://devhints.io/docker

    Go to previous directory

    cd -
    

    Subshells

    (cd somedir; echo "I'm now in $PWD")
    pwd # still in first directory
    

    Conditionals execution

    git commit && git push
    git commit || echo "commit failed"
    

    Conditionals

    if [ -z "$string" ]; then
        echo "empty"
    elif [ -n "$string" ]; then
        echo "not empty"
    

    Function arguments

    $#  Number of arguments
    $*  All arguments
    $@  All arguments, starting from first
    $1  First argument
    }
    echo "You are $(get_name)"
    

    Function return values

    get_name() {
      echo "John" # return
    }
    echo "You are $(get_name)"
    

    Brace expansion

    echo {a,b}.js
    echo {a..z}.js
    

    String quotes

    NAME="Hohn"
    echo "Hi $NAME"
    echo 'Hi $NAME'
    

    Shell execution

    echo "I'm in $(pwd)"
    echo "I'm in `pwd`"
    

    Length

    ${#FOO} Length of $FOO
    

    Default values

    ${FOO:-val} $FOO, or val if not set
    ${FOO:=val} Set $FOO to val if not set
    ${FOO:+val} val if $FOO is set
    ${FOO:?message} Show error message and exit if $FOO is not set
    

    Loops

    for i in /etc/rc.*; do
      echo $i
    done
    

    Printf

    printf "Hello %s, I'm %s" Sven Olga
    #=> "Hello Sven, I'm Olga
    

    Special variables

    $?  Exit status of last task
    $!  PID of last background task
    $$  PID of shell
    

    File conditions

    [ -e FILE ] Exists
    [ -r FILE ] Readable
    [ -h FILE ] Symlink
    [ -d FILE ] Directory
    [ -w FILE ] Writable
    [ -s FILE ] Size is > 0 bytes
    [ -f FILE ] File
    [ -x FILE ] Executable
    

    Defining arrays

    Fruits=('Apple' 'Banana' 'Orange')
    Fruits[0]="Apple"
    Fruits[1]="Banana"
    Fruits[2]="Orange"
    
    echo ${Fruits[0]}           # Element #0
    echo ${Fruits[@]}           # All elements, space-separated
    echo ${#Fruits[@]}          # Number of elements
    echo ${#Fruits}             # String length of the 1st element
    echo ${#Fruits[3]}          # String length of the Nth element
    echo ${Fruits[@]:3:2}       # Range (from position 3, length 2)
    
    for i in "${arrayName[@]}"; do
      echo $i
    done
    

    相关文章

      网友评论

          本文标题:shell cheatsheet

          本文链接:https://www.haomeiwen.com/subject/qcizqqtx.html