Define function in unix/linux command line (e.g. B

2019-04-04 13:07发布

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:

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. (Everything coming up is just tutorials on bash functions).

4条回答
一纸荒年 Trace。
2楼-- · 2019-04-04 13:48

Don't use ls | wc -l as it may give you wrong results if file names have newlines in it. You can use this function instead:

numresults() { find "$1" -mindepth 1 -printf '.' | wc -c; }
查看更多
在下西门庆
3楼-- · 2019-04-04 13:59

Quoting my answer for a similar question on Ask Ubuntu:

Functions in bash are essentially named compound commands (or code blocks). From 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:

numresults(){ ls "$1"/RealignerTargetCreator | wc -l; }
查看更多
做个烂人
4楼-- · 2019-04-04 14:04

You can also count files without 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 ...)

查看更多
Fickle 薄情
5楼-- · 2019-04-04 14:10

The easiest way maybe is echoing what you want to get back.

function myfunc()
{
    local  myresult='some value'
    echo "$myresult"
}

result=$(myfunc)   # or result=`myfunc`
echo $result

Anyway here you can find a good how-to for more advanced purposes

查看更多
登录 后发表回答