Guest User

Untitled

a guest
Nov 24th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. ## Arrays
  2. ```bash
  3. distro=("redhat" "debian" "gentoo")
  4. echo ${distro[0]}
  5. echo ${distro[2]} # will print gentoo
  6. echo ${#distro[@]} # print array size, here 3
  7.  
  8. tLen=${#distro[@]}
  9. for (( i=0; i<${tLen}; i++ ));
  10. do
  11. echo ${distro[$i]}
  12. done
  13. ```
  14.  
  15. ## Basic
  16. ```bash
  17. foo="asdf"
  18. echo${#foo} # 4 - lenght of foo
  19. ```
  20. ### Incrementation
  21. ```bash
  22. i=0
  23. ((i++)) # i=1
  24. ((i+=3)) # i=4
  25. ```
  26. ### Command substitution
  27. ```bash
  28. $(cmd) # POSIX
  29. `cmd` # more or less obsolete for Bash
  30. $((cmd)) # arithmetic expansion
  31. $( (cmd) ) # explicit subshell (cmd) inside the command substitution $( )
  32. ```
  33. #### Nesting
  34. ```bash
  35. echo `echo `ls`` # INCORRECT
  36. echo `echo \`ls\`` # CORRECT
  37. echo $(echo $(ls)) # CORRECT
  38. echo "$(echo "$(ls)")" # nested double-quotes
  39. ```
  40. ### Condition execution
  41. ```bash
  42. git commit && git push
  43. git commit || echo "Commit failed"
  44. ```
  45.  
  46. ## Parameter expansions
  47. ### Substitution
  48. ```bash
  49. STR="/path/to/foo.cpp"
  50. # ${FOO%suffix} Remove first suffix
  51. echo ${STR%.cpp} # /path/to/foo
  52. echo ${STR%.cpp}.o # /path/to/foo.o
  53. # ${FOO%%suffix} Remove long suffix
  54.  
  55. # ${FOO#prefix} Remove prefix
  56. echo ${STR#*/} # path/to/foo.cpp
  57. # ${FOO##prefix} Remove long prefix
  58. echo ${STR##*.} # cpp (extension)
  59. echo ${STR##*/} # foo.cpp (basepath)
  60. # ${FOO/from/to} Replace first match
  61. echo ${STR/foo/bar} # /path/to/bar.cpp
  62. name="Johnny"
  63. echo ${name/n/N} #=> "JohNny"
  64. # ${FOO//from/to} Replace all
  65. echo ${name/n/N} #=> "JohNNy"
  66. # ${FOO/%from/to} Replace suffix
  67. BASE=${STR##*/} #=> "foo.cpp" (basepath)
  68. DIR=${SRC%$BASE} #=> "/path/to" (dirpath)
  69. # ${FOO/#from/to} Replace prefix
  70.  
  71. ```
  72. ### Substrings
  73. ```bash
  74. name="Johnny"
  75. # ${FOO:0:2} Substring (position, length)
  76. echo ${name:0:2} #=> "Jo"
  77. echo ${name:0:-2} #=> "John"
  78. ```
  79. ### Default values
  80. ```bash
  81. # ${FOO:-val} return $FOO, or val if $FOO not set
  82. unset foo
  83. echo ${food:-Cake} #=> "Cake"
  84. echo $food #=> ""
  85. food="Pie"
  86. echo ${food:-Cake} #=> "Pie"
  87. # ${FOO:=val} Set $FOO to val if $FOO not set
  88. unset foo
  89. echo ${food:=Cake} #=> "Cake"
  90. echo $food #=> "Cake"
  91. food="Pie"
  92. echo ${food:=Cake} #=> "Pie"
  93. # ${FOO:+val} return val if $FOO is set
  94. unset foo
  95. echo ${food:+Cake} #=> ""
  96. echo $food #=> ""
  97. food="Pie"
  98. echo ${food:+Cake} #=> "Cake"
  99. # ${FOO:?message} Show error message and exit if $FOO is not set
Add Comment
Please, Sign In to add comment