define a function-like macro in bash
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.
Yes, only you should call it with F sth
:
F()
{
echo "$1" > a.txt
}
Read more here.
F () {
echo "$1" > a.txt
}
You don't use parentheses when you call it. This is how you call it:
F "text to save"