微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在unix / linux命令行例如BASH中定义函数

有时候,我有一个单独的内容,我为了一个特定的任务重复了很多次,但是可能永远不会以完全相同的forms再次使用。 它包含一个我从目录列表中粘贴的文件名。 之间的某处并创build一个bash脚本我想也许我可以在命令行创build一个单线程函数,如:

numresults(){ ls "$1"/RealignerTargetCreator | wc -l }

我已经尝试了一些使用eval的方法,使用了numresults=function... ,但还没有find正确的语法,到目前为止还没有发现任何东西。 (所有的东西都是关于bash函数的教程)。

从bash shell启动一个新的bash shell

在Unix(或Windows)中,如何使用(最好是未命名的)pipe道将一个进程的stdout发送到多个进程?

以只包含冒号的行结尾的shell脚本?

将ssh -V保存到variables中

检查传递的参数是否是BASH中的文件或目录

引用我在Ask Ubuntu上的类似问题的答案 :

bash中的函数本质上被命名为复合命令(或代码块)。 从man bash :

Compound Commands A compound command is one of the following: ... { list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is kNown as a group command. ... Shell Function DeFinitions A shell function is an object that is called like a simple command and executes a compound command with a new set of positional parameters. ... [C]ommand is usually a list of commands between { and },but may be any command listed under Compound Commands above.

没有理由,只是语法。

在wc -l之后用分号尝试:

numresults(){ ls "$1"/RealignerTargetCreator | wc -l; }

不要使用ls | wc -l ls | wc -l因为如果文件名中有换行符,它可能会给你错误的结果。 你可以使用这个函数来代替:

numresults() { find "$1" -mindepth 1 -printf '.' | wc -c; }

您也可以不find文件来计数文件。 使用数组,

numresults () { local files=( "$1"/* ); echo "${#files[@]}"; }

或使用位置参数

numresults () { set -- "$1"/*; echo "$#"; }

为了匹配隐藏的文件

numresults () { local files=( "$1"/* "$1"/.* ); echo $(("${#files[@]}" - 2)); } numresults () { set -- "$1"/* "$1"/.*; echo $(("$#" - 2)); }

(从结果中减去2补偿.. )

最简单的方法可能是回应你想要回来的东西。

function myfunc() { local myresult='some value' echo "$myresult" } result=$(myfunc) # or result=`myfunc` echo $result

无论如何, 在这里你可以找到一个很好的方法来达到更高级的目的

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐