Like they said in the comments, you don't, really.
Well, you could do that with eval
, but you'd be in trouble with quoting/escaping everything else on that command line.
There's some things you can do with functions though: to run a given simple command under a redirection; or to just write a message to stderr:
#!/bin/bash
tostderr() {
"$@" >&2
}
warn() {
local IFS=" "
printf "%s\n" "$*" >&2
}
tostderr printf "warning: %s\n" "something happened"
warn another thing to warn about
Emphasis on the simple command on the first one, it's not eval
and you can't have shell syntax within the command. E.g. in tostderr foo | bar
it redirects the output of just foo
(past the pipe to stderr), and tostderr (foo | bar)
won't work.
If you were on zsh, and really wanted to, you could use a global alias to add the redirection (but some might think this is bordering on obfuscated coding):
#/usr/bin/zsh
alias -g TOSTDERR='>&2'
echo something bad happened TOSTDERR
warn() { local IFS=' '; printf '%s\n' "$*" >&2; }
as"$*"
joins args with the first character of$IFS
. Orwarn() print -ru2 -- "$@"
in ksh/zsh. See also thesyserror
builtin inzsh
'szsh/system
module. – Stéphane Chazelas Oct 28 '21 at 08:25eval
for this -- it fixes this problem, but opens the door to a whole new and much messier bunch of problems. BTW, shellcheck.net does spot>2&
(and similar mistakes), along with many others -- I recommend running your scripts through it as a general sanity-check. – Gordon Davisson Oct 28 '21 at 08:36sudo apt install shellcheck
– Raimo Oct 28 '21 at 10:16