03 函数和文本描述符

68 阅读1分钟

03 函数和文本描述符

函数的基本使用

基本形式

func01() {
    echo "这是第一个函数内容"
}
func01

function sum {
    read -p "输入一个数字:" value
    echo $[ $value *2 ]
}
echo "计算结果是:$(sum)"

接收字符串数组

#!/bin/bash

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"

引用库文件

新建一个库文件:myfuncs.sh

# my script functions

function addem {
   echo $[ $1 + $2 ]
}

function multem {
   echo $[ $1 * $2 ]
}

function divem {
   if [ $2 -ne 0 ]
   then
      echo $[ $1 / $2 ]
   else
      echo -1
   fi
}
$

引用库文件

#!/bin/bash
# 脚本在其他目录下:. /opt/myfucs.sh
# 脚本文件和库文件在同一目录下,注意空格
. myfuncs.sh

value1=10
value2=5
result1=$( addem $value1 $value2 )
result2=$( multem $value1 $value2 )
result3=$( divem $value1 $value2 )
echo "The result of adding them is: $result1"
echo "The result of multiplying them is: $result2"
echo "The result of dividing them is: $result3"

文件描述符

使用文件描述符读取文件信息

#!/bin/bash
# 0 表示标准输入(STDIN), 1 表示标准输出(STDOUT),2 表示错误输出(STDERR)

exec 0< testfile # 将 testfile 文件内容输入到 STDIN 中
count=1

while read line # 从 STDIN 中读取数据
do
   echo "Line #$count: $line"
   count=$[ $count + 1 ]
done

使用文件描述符重定向

# 使用 ls 查询两个文件夹信息
# 文件存在就把信息存到 exist.txt,文件不存在就把错误信息存到 error.txt
$ ls -al /etc/passwd /etc/aassd 2> error.txt 1>exist.txt

$ cat exist.txt
-rw-r--r--. 1 root root 925 Oct 17  2022 /etc/passwd

$ cat error.txt
ls: cannot access /etc/aassd: No such file or directory

使用 exec 命令批量重定向

#!/bin/bash
exec 2>testerror # 错误信息记录到 testerror 文件
exec 1>testout # 标准输出记录到 testout 文件

echo "This output should go to the testout file"    # 标准输出默认记录到 testout 文件中,不显示在终端
echo "but this should go to the testerror file" >&2 # 手动将信息记录到 testerror 文件中,需要添加“&”符号

重定向文件描述符

#!/bin/bash
# storing STDOUT, then coming back to it

exec 3>&1 # 将 3 重定向到 1
exec 1>test14out # 所有标准输出都会被重定向到文件中,不显示在终端

echo "This should store in the output file"
echo "along with this line."

exec 1>&3 # 将 1 重定向到 3 ,使得标准输出内容正常显示在终端

echo "Now things should be back to normal"

exec 3>&- # 关闭描述符,关闭之后不能再使用,否则会报错
# echo "error" >&3 # 会提示错误 “Bad file descriptor”

/dev/null 文件的使用

# demo.sh存在,会显示相关信息,noexit.txt不存在,会显示一行报错信息
$ ls -al demo.sh noexist.txt 

# 将报错信息输出到 /dev/null,报错信息都会被丢弃
$ ls -al demo.sh noexist.txt 2> /dev/null

# 将 demo.sh 文件内容清空
$ cat /dev/null > demo.sh