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

aba*_*ter 16 unix linux bash shell

有时我会为一项特定的任务重复多次,但很可能永远不会再使用完全相同的形式.它包含我从目录列表中粘贴的文件名.在介于两者之间并创建一个bash脚本我想也许我可以在命令行创建一个单行函数,如:

numresults(){ ls "$1"/RealignerTargetCreator | wc -l }
Run Code Online (Sandbox Code Playgroud)

我尝试了一些像使用eval,使用的东西numresults=function...,但没有偶然发现正确的语法,到目前为止还没有在网上找到任何东西.(所有内容都是关于bash函数的教程).

mur*_*uru 22

在Ask Ubuntu上引用对类似问题的回答:

函数in 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.
Run Code Online (Sandbox Code Playgroud)

没有理由给出,它只是语法.

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

numresults(){ ls "$1"/RealignerTargetCreator | wc -l; }
Run Code Online (Sandbox Code Playgroud)

  • 分号是必要的,因为`}`不是控制字符,也不会终止命令.注意`echo}`只是输出文字字符串. (2认同)