[英]Define function in unix/linux command line (e.g. BASH)
Sometimes I have a one-liner that I am repeating many times for a particular task, but will likely never use again in the exact same form.有时我会为一项特定任务重复多次,但可能永远不会以完全相同的形式再次使用。 It includes a file name that I am pasting in from a directory listing.
它包含我从目录列表中粘贴的文件名。 Somewhere in between and creating a bash script I thought maybe I could just create a one-liner function at the command line like:
介于两者之间并创建一个 bash 脚本,我想也许我可以在命令行中创建一个单行函数,例如:
numresults(){ ls "$1"/RealignerTargetCreator | wc -l }
I've tried a few things like using eval, using numresults=function...
, but haven't stumbled on the right syntax, and haven't found anything on the web so far.我尝试了一些方法,例如使用 eval、使用
numresults=function...
,但没有偶然发现正确的语法,并且到目前为止还没有在网上找到任何东西。 (Everything coming up is just tutorials on bash functions). (接下来的一切都只是关于 bash 函数的教程)。
Quoting my answer for a similar question on Ask Ubuntu:在 Ask Ubuntu 上引用我对类似问题的回答:
Functions in
bash
are essentially named compound commands (or code blocks).bash
中的函数本质上是命名的复合命令(或代码块)。 Fromman 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.
There's no reason given, it's just the syntax.
没有给出任何理由,这只是语法。
Try with a semicolon after wc -l
:尝试在
wc -l
后使用分号:
numresults(){ ls "$1"/RealignerTargetCreator | wc -l; }
Don't use ls | wc -l
不要使用
ls | wc -l
ls | wc -l
as it may give you wrong results if file names have newlines in it. ls | wc -l
因为如果文件名中有换行符,它可能会给你错误的结果。 You can use this function instead:您可以改用此功能:
numresults() { find "$1" -mindepth 1 -printf '.' | wc -c; }
You can also count files without find
.您也可以在没有
find
情况下计算文件。 Using arrays,使用数组,
numresults () { local files=( "$1"/* ); echo "${#files[@]}"; }
or using positional parameters或使用位置参数
numresults () { set -- "$1"/*; echo "$#"; }
To match hidden files as well,为了匹配隐藏文件,
numresults () { local files=( "$1"/* "$1"/.* ); echo $(("${#files[@]}" - 2)); }
numresults () { set -- "$1"/* "$1"/.*; echo $(("$#" - 2)); }
(Subtracting 2 from the result compensates for .
and ..
.) (从结果中减去 2 补偿
.
和..
。)
You can get a你可以得到一个
bash: syntax error near unexpected token `('
error if you already have an alias
with the same name as the function you're trying to define.如果您已经有一个与您尝试定义的函数同名的
alias
,则会出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.