Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define a function-like macro in bash

Is it possible to define a macro-function in bash so when I write:

F(sth);

bash runs this:

echo "sth" > a.txt;
like image 329
a-z Avatar asked Apr 17 '12 06:04

a-z


2 Answers

Arbitrary syntax can't be made to do anything. Parentheses are metacharacters which have special meaning to the parser, so there's no way you can use them as valid names. The best way to extend the shell is to define functions.

This would be a basic echo wrapper that always writes to the same file:

f() {
    echo "$@"
} >a.txt

This does about the same but additionally handles stdin - sacrificing echo's -e and -n options:

f() {
    [[ ${1+_} || ! -t 0 ]] && printf '%s\n' "${*-$(</dev/fd/0)}"
} >a.txt

Which can be called as

f arg1 arg2...

or

f <file

Functions are passed arguments in the same way as any other commands.

The second echo-like wrapper first tests for either a set first argument, or stdin coming from a non-tty, and conditionally calls printf using either the positional parameters if set, or stdin. The test expression avoids the case of both zero arguments and no redirection from a file, in which case Bash would try expanding the output of the terminal, hanging the shell.

like image 127
ormaaj Avatar answered Sep 28 '22 06:09

ormaaj


F () {
  echo "$1" > a.txt
}

You don't use parentheses when you call it. This is how you call it:

F "text to save"
like image 31
Emil Vikström Avatar answered Sep 28 '22 07:09

Emil Vikström