sh Bash特定的功能和语法cheatsheet

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sh Bash特定的功能和语法cheatsheet相关的知识,希望对你有一定的参考价值。

# Redirect stderr to stdout
find / -name foo > output.txt 2>&1
find -name test.sh 2>&1 | tee /tmp/output.txt
# Loop over array
services=(postfix dovecot saslauthd postfwd)
for s in ${services[@]}; do
  echo "$s"
done

# Infinite loop
a=0; 
while [ 1 ]; do 
  let 'a+=1'
  echo "$a"
  sleep 1
done

# Replace in bash curly substitution
echo ${VAR/test/string}    # replaces only first occurence
echo ${VAR//test/string}   # replaces all occurences

# Length of a string
echo ${#TEST}

# Trims png and appends jpg
echo "${FILENAME%png}jpg"

# Variable setting
TEST="test"
echo ${TEST-not set}       # output "test"
unset TEST
echo ${TEST-not set}       # output "not set"
echo ${TEST+set}           # outputs $TEST if it is set

# Use as separate arguments
echo {one,two,red,blue}
echo {one,two,red,blue}

# Remove extension
${filename%.*} (remove extension)

# Sequences
echo {1..10..2}
> 1 3 5 7 9
echo {10..1..2}
> 10 8 6 4 2
echo {a..z..3}
> a d g j m p s v y

# Create 2 files with one line (brace expansion)
mkdir -p /srv/{salt,pillar}

# Resources:
# http://stackoverflow.com/questions/8748831/when-do-we-need-curly-braces-in-variables-using-bash
# http://wiki.bash-hackers.org/syntax/expansion/brace
# https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html
# http://www.thegeekstuff.com/2010/06/bash-shell-brace-expansion/
# http://mfitzp.io/article/use-bash-brace-expansion-to-save-hoursdays/
# http://www.linuxjournal.com/article/7385
# http://ryanuber.com/05-12-2010/bash-variable-expansion-tricks.html
# Show timestamps in bash history
HISTTIMEFORMAT="%d/%m/%y %T "
# Exit on error
set -e
# Exit if variable was not set
set -u
# Exit when command in pipe fails
set -o pipefail
# Print every command executed with variable interpolation
set -x

以上是关于sh Bash特定的功能和语法cheatsheet的主要内容,如果未能解决你的问题,请参考以下文章

sh Bash - cheatsheet

sh Bash Cheatsheet

sh Bash Cheatsheet

sh #unix #bash #cheatsheet

sh 适用于UNIX系统的Bash CheatSheet

sh 适用于UNIX系统的Bash CheatSheet