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).
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.
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.
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.
Quoting my answer for a similar question on Ask Ubuntu:
Functions in
bash
are essentially named compound commands (or code blocks). Fromman 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; }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With