linux - 无法访问 2>&1 : How to treat variable content as a redirection not as filename

标签 linux bash io-redirection

如何根据可变内容控制进程输出重定向?我试过以下,但它将 $redirect 的内容视为文件名而不是重定向本身。

$ 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

最佳答案

如果您接受更改命令的顺序,这里有一种实现您想要的方法:使用别名。别名通常不受欢迎,而且,正如 Bash 手册中所述,对于几乎所有用途,别名都被 shell 函数所取代。

看来我们正处于几乎的突破口中:

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

并且没有eval

关于linux - 无法访问 2>&1 : How to treat variable content as a redirection not as filename,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28347210/

相关文章:

linux - Linux Bash 中的模式匹配

bash - 如何使用 sed 将路径字符串上的 "/"替换为 "\/"?

bash - 我应该使用什么方法在 bash 脚本中使用 'stderr' 将错误消息写入 'printf'?

c++ - 替代控制台输出流

python - 使用 python 进行输入重定向

python - 使用 python 的远程 shell

linux - 如何排序和忽略空格?

php - 在 Linux 中的 PHP 和 C 可执行文件之间传递数据

bash - 为什么 Bash 的 $RANDOM 没有在某些机器上播种(?)?

bash - 将字符串中的 "/"替换为 "${parameter/pattern/string}"?