1

Similar question, but no answer: How can we run a command stored in a variable?

How to do the following in bash script?

error=">&2"
echo 'something went wrong' $error

instead of

echo 'something went wrong' >&2

Why?
Because if you typo it like >2&, it works normal but writes error messages to a file called 2.

AdminBee
  • 22,803
Raimo
  • 11

1 Answers1

1

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


ilkkachu
  • 138,973