Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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).

like image 685
abalter Avatar asked Feb 17 '16 19:02

abalter


People also ask

How do you define a function in Unix?

Creating FunctionsThe name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.

Can you define functions in bash?

Defining Bash FunctionsFunctions may be declared in two different formats: The first format starts with the function name, followed by parentheses. This is the preferred and more used format. The second format starts with the reserved word function , followed by the function name.

How do you define a function in Linux?

Function is a command in linux which is used to create functions or methods. 1. using function keyword : A function in linux can be declared by using keyword function before the name of the function. Different statements can be separated by a semicolon or a new line.


2 Answers

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; } 
like image 112
muru Avatar answered Oct 19 '22 09:10

muru


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; } 
like image 40
anubhava Avatar answered Oct 19 '22 07:10

anubhava