gpt4 book ai didi

bash - 在shell中的另一个函数中调用时如何将参数传递给函数

转载 作者:行者123 更新时间:2023-12-04 18:37:42 24 4
gpt4 key购买 nike

我有带有 2 个函数的 shell 脚本,如下所示:

lines(){
while IFS="" read -l
do
line=$(wc -l < "something.txt")
if [ "$line" = "$1" ] ; then
do something...
echo "lines are: "$l""
else

#calling files function here
files
do something...
fi
done<something.txt
}
files(){
do something....
echo "something...\n""$(lines "$1")"
}
####Main
case "$1" in
lines)
shift
lines "$1"
;;
*)
esac

我正在尝试在 ubuntu 机器上运行这样的脚本:
 sh files.sh line 3

我有一些 if 操作在哪里
files我想调用 lines功能。当它被调用并返回执行 lines() 中的操作时,我试图从命令行传递的参数 3"$1"被传递为 null (empty)有人可以帮助我如何拥有 lines函数读取我从命令行传递的参数
谢谢

最佳答案

最简单的方法是创建一个全局数组变量来保留您原来的命令行参数:

#!/usr/bin/env bash
[ "$BASH_VERSION" ] || { echo "ERROR: This script requires bash" >&2; exit 1; }

args=( "$0" "$@" )

func1() { func2 "local-arg1" "local-arg2"; }
func2() { echo "Function argument 1 is $1; original argument 2 is ${args[2]}"; }
func1

...将,如果被称为 ./scriptname global-arg1 global-arg2 ,作为输出发出:

Function argument 1 is local-arg1; original argument 2 is global-arg2

关于bash - 在shell中的另一个函数中调用时如何将参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49928805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com