收集的48个Shell脚本小技巧

2019-09-23 09:36:26丽君

echo "now redirecting all output to another location" &>/dev/null

问题就来了,如果我们要将所有的输出都重定向到某个文件呢?我们都不希望每次输出的时候都重定向一下吧,正所谓,山人自有妙计。我们可以用exec 来永久重定向,如下所示:
#!/bin/bash
#redirecting output to different locations
exec 2>testerror
echo "This is the start of the script"
echo "now redirecting all output to another location"

exec 1>testout
echo "This output should go to testout file"
echo "but this should go the the testerror file" >& 2

输出结果如下所示:
This is the start of the script
now redirecting all output to another location
lalor@lalor:~/temp$ cat testout
This output should go to testout file
lalor@lalor:~/temp$ cat testerror
but this should go the the testerror file
lalor@lalor:~/temp$

以追加的方式重定向:
exec 3 >> testout
取消重定向:
exec 3> -

47. 函数

任何地方定义的变量都是全局变量,如果要定义局部变量,需加local 关键字
shell中的函数也可以用递归
#!/bin/bash

  function factorial {
      if [[ $1 -eq 1 ]]; then
          echo 1
      else
          local temp=$[ $1 - 1 ]
          local result=`factorial $temp`
          echo $[ $result * $1 ]
      fi
  }

  result=`factorial 5`
  echo $result

创建函数库

将函数定一个在另一个文件,然后通过source 命令加载到当前文件

在命令行使用函数

将函数定义在~/.bashrc 中即可

向函数传递数组

#!/bin/bash
  #adding values in an array

  function addarray {
      local sum=0
      local newarray
      newarray=(`echo "$@"`)
      for value in ${newarray[*]}
      do
          sum=$[ $sum+$value ]
      done
      echo $sum
  }

  myarray=(1 2 3 4 5)
  echo "The original array is: ${myarray[*]}"
  arg1=`echo ${myarray[*]}`
  result=`addarray $arg1`
  echo "The result is $result"

48.正则表达式

匹配中文字符的正则表达式:[u4e00-u9fa5]
评注:匹配中文还真是个头疼的事,有了这个表达式就好办了