Cannot access 2> and 1: how to handle variable content as a redirect not as a file name

How can I control the redirection of process output based on the contents of a variable? I tried following, but it treats the contents $redirectas the file name instead of the redirect itself.

$ redirect="2>&1 >/dev/null"
$ ls -la $redirect
ls: cannot access 2>&1: No such file or directory
$ redirect=""
$ ls -la $redirect
total 376
drwx------ 1 wakatana users   4096 Feb  5 15:32 .
drwx------ 1 wakatana users   4096 Feb  2 18:44 ..
-rw------- 1 wakatana users    390 Feb  5 13:34 .bashrc
+4
source share
3 answers

Here you can achieve what you want, provided that you agree to change the order of your team: use an alias. Aliases are usually frowned and, as stated in the Bash manual, for almost all purposes, aliases are replaced by shell functions.

It seems we are almost in violation here:

$ alias redirect='2>&1 > /dev/null'
$ redirect ls
$

eval.

+4

ls - , ( ) 2>&1 >/dev/null, ls '2>&1' '>/dev/null'. , , - . eval :

 eval ls -la $redirect

, POSIX

  • , , 3 4.

  • , , . - , , - .

  • , .

  • , , , .

, , :

$ redirect=">file"
$ echo foo $redirect
foo >file
$ eval echo foo $redirect
$ cat file
foo

Etan, eval , redirect. , redirect='; rm -rf $HOME'.

+3

2>&1 , :

$redirect="2>&1 >/dev/null"

$redirect=">/dev/null 2>&1"

:

ls -al , :

$redirect="ls -al >/dev/null 2>&1"
eval $redirect

The goal 2>&1in the end is to redirect all errors generated by the command, as well as the first redirection.

+1
source

All Articles