我对shell编程非常陌生,我正在尝试编写一个shell脚本,将grep或awk模式过滤输出赋值给bash shell中的命令行参数。
a.sh
source ./b.sh
called a function like // a(function name) parameter1 parameter2
b.sh
function a{
$2=grep -ai "some string" a.txt(parameter 1)
echo "$2"
}我想做喜欢,但它不让我做。
这有可能吗?
发布于 2013-06-05 22:18:29
在bash中,您不能以调用方可以读取该值的方式设置位置参数。如果你想从一个函数中“返回”一个字符串,你必须把它写到stdout中,如下所示:
function myfunc()
{
echo "test"
}
VAR=$(myfunc)当运行上述代码时,测试将包含字符串‘VAR’。
发布于 2013-06-05 22:20:04
对于参考问题,请查看man页面;例如,man bash、man grep等。对于像function这样的内部shell命令,有一个内置的bash,它具有类似的功能,称为help,例如help function。
要设置位置参数,可以使用内置的set。例如,set -- "a b" "c d"将$1设置为a b,将$2设置为c d。
有关bash编程的实用介绍,请参阅Bash wiki。它是最好的Bash资源。
发布于 2013-06-05 22:21:54
你不能给位置参数赋值,但是你可以这样做:
function myf {
#do something with $1,$2, etc
}
FOO=$(awk command)
BAR=$(other command)
myf $FOO $BAR #the function will use $FOO and $BAR as $1 and $2 positional parameters因此,在本例中,您可以通过使用变量(FOO和BAR)将这些命令的内容传递给函数myf。您甚至可以在不调用myf $(some command)的情况下执行此操作,但我编写它的方式提高了可读性。
https://stackoverflow.com/questions/16942279
复制相似问题