当前位置: 首页 > 工具软件 > bash-guide > 使用案例 >

Advanced Bash-Scripting Guide 读书笔记--Chapter 3 Special Characters

万俟鸿波
2023-12-01
  • Comments #
    从#到行尾,表示注释。可以通过(‘”)转义。
  • Command separator ;
    表示命令结束,用来分割命令。一般是一行一个命令,但是要在一行中包含多个命令的话,需要把它加入其中。
echo hello; echo there
if [ -x "$filename" ]; then    #  Note the space after the semicolon.
  echo "File $filename exists."; cp $filename $filename.bak
else                
  echo "File $filename not found."; touch $filename
fi; echo "File test complete."
  • case 结束符 ;;
case "$variable" in
  abc)  echo "\$variable = abc" ;;
  xyz)  echo "\$variable = xyz" ;;
esac
  • test operator
(( var0 = var1<98?9:21 ))
#                

# if [ "$var1" -lt 98 ]
# then
#   var0=9
# else
#   var0=21
# fi
  • Variable substitution $
    变量前缀
var1=5
var2=23skidoo

echo $var1     # 5
echo $var2     # 23skidoo
  • process ID variable $$
    保存着进程id
  • exit status variable $?
    保存着上一个命令完成的状态,即exit X 中的X(X是一个数字)
  • redirection > &> >& >> < <>
    重定向
    scriptname >filename 把scriptname脚本运行的结果重定向到filename的文件,如果filename的文件已经存在,则覆盖
    command &>filename 把command的stdout和stderr重定向到filename的文件中
    command >&2 把command的stdout重定向到stderr
    scriptname >>filename 把scriptname脚本执行的内容追加到filename的文件中,如果文件不存在,则创建

  • word boundary \<, >
    正则表达式中的字符边界

grep '\<the\>' textfile
  • redirection from/to stdin or stdout -
(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -)
# Move entire file tree from one directory to another
# [courtesy Alan Cox <a.cox@swansea.ac.uk>, with a minor change]

# 1) cd /source/directory
#    Source directory, where the files to be moved are.
# 2) &&
#   "And-list": if the 'cd' operation successful,
#    then execute the next command.
# 3) tar cf - .
#    The 'c' option 'tar' archiving command creates a new archive,
#    the 'f' (file) option, followed by '-' designates the target file
#    as stdout, and do it in current directory tree ('.').
# 4) |
#    Piped to ...
# 5) ( ... )
#    a subshell
# 6) cd /dest/directory
#    Change to the destination directory.
# 7) &&
#   "And-list", as above
# 8) tar xpvf -
#    Unarchive ('x'), preserve ownership and file permissions ('p'),
#    and send verbose messages to stdout ('v'),
#    reading data from stdin ('f' followed by '-').
#
#    Note that 'x' is a command, and 'p', 'v', 'f' are options.
#
# Whew!

# More elegant than, but equivalent to:
#   cd source/directory
#   tar cf - . | (cd ../dest/directory; tar xpvf -)
#
#     Also having same effect:
# cp -a /source/directory/* /dest/directory
#     Or:
# cp -a /source/directory/* /source/directory/.[^.]* /dest/directory
#     If there are hidden files in /source/directory.
 类似资料: