0
点赞
收藏
分享

微信扫一扫

【Qt QML入门】第一个Quick应用

北溟有渔夫 2023-07-13 阅读 37

文章目录


在这里插入图片描述

🍔函数

如果想获取函数的输出结果,可以通过echo输出到stdout中,然后通过$(function_name)来获取stdout中的结果
函数的return值可以通过$?来获取

[function] func_name(){ # function关键字可以省略
	语句1
	语句2
	...
}

⭐不获取return值和stdout值

#! /bin/bash
func() {
    name=fufu
    echo "Hello $name"
}

func

在这里插入图片描述

⭐获取return值和stdout值

#! /bin/bash
func() {
    name=fufu
    echo "Hello $name"

    return 123
}

output=$(func)
ret=$?		#函数的return值可以通过 $? 来获取

echo "output = $output"
echo "return = $ret"

在这里插入图片描述

🌺函数的输入参数

在函数中,$1表示第一个输入参数,$2表示第二个输入参数,以此类推

#! /bin/bash
func() {  # 递归计算 $1 + ($1 - 1) + ($1 - 2) + ... + 0
    word=""
    while [ "${word}" != 'y' ] && [ "${word}" != 'n' ]
    do
        read -p "要进入func($1)函数吗?请输入y/n:" word
    done

    if [ "$word" == 'n' ]
    then
        echo 0
        return 0
    fi  

    if [ $1 -le 0 ] 
    then
        echo 0
        return 0
    fi  

    sum=$(func $(expr $1 - 1))
    echo $(expr $sum + $1)
}

echo $(func 10)

在这里插入图片描述

🌺函数的局部变量

可以在函数里面定义局部变量,作用范围仅在当前函数里面
可以在递归函数中定义局部变量

local 变量名=变量值

例如

#! /bin/bash

func() {
    local name=fufu
    echo $name
}
func

echo $name

在这里插入图片描述

🍔exit命令

  • exit命令用来退出当前shell进程,并返回一个退出状态,所以$?可以接收这个退出状态
  • exit命令可以接受一个整数值作为参数,代表退出状态。如果不指定,默认状态值为0
  • exit退出状态

⭐示例

创建脚本abc.sh

#! /bin/bash

if [ $# -ne 1 ]  # 如果传入参数个数等于1,则正常退出;否则非正常退出。
then
    echo "arguments not valid"
    exit 1
else
    echo "arguments valid"
    exit 0
fi

在这里插入图片描述

🍔文件重定向

每个进程默认打开3个文件描述符

  • stdin 标准输入,从命令行读取数据,文件描述符为0
  • stdout标准输出,向命令行输出数据,文件描述符为1
  • stderr标准错误输出,向命令行输出数据,文件描述符为2

重定向命令列表

命令说明
command > filestdout重定向到file
command < filestdin重定向到file
command >> filestdout以追加方式重定向到file
command n > file将文件描述符n重定向到file
command n >> file将文件描述符n以追加方式重定向到file

⭐示例

输入和输出重定向

echo -e "Hello \c" > output.txt  # 将stdout重定向到output.txt中
echo "World" >> output.txt  # 将字符串追加到output.txt中

read str < output.txt  # 从output.txt中读取字符串

echo $str  # 输出结果:Hello World

同时重定向stdin和stdout
创建bash脚本

#! /bin/bash

read a
read b

echo $(expr "$a" + "$b")

创建input.txt,里面的内容为:

3
4

执行命令

在这里插入图片描述

🍔引入外部脚本

类似于C/C++的include操作,bash也可以引入其他文件中的代码

. filename  #注意文件和点之间有一个空格

或者

source filename

⭐示例

创建test1.sh,内容为

#! /bin/bash

name=fufu  #定义变量

然后创建test2.sh,内容为

#! /bin/bash

source test1.sh # 或 . test1.sh

echo My name is: $name  # 可以使用test1.sh中的变量

在这里插入图片描述

举报

相关推荐

0 条评论