linux - 如何使用 bash 写入除现有常规文件以外的任何文件?

标签 linux bash shell

我做了以下尝试.. 徒劳无功:

  1. hello.sh 使用“test -f”
#! /bin/bash
test -f $1 && exit 1 || echo "hello" > $1

不幸的是,$ ./hello.sh/dev/stdout > non_existent 没有写入。

  1. hello2.sh 使用“set -C”
#! /bin/bash
set -C; echo "hello" > $1

此外,$ ./hello2.sh/dev/stdout > non_existent 仍然不起作用。

我猜想在重定向时,bash 会调用 freopen("/dev/stdout", "w", $1),这错误地使 /dev/stdout 看起来像一个现有的常规文件。

我该如何解决这个问题?

最佳答案

是的,只需在(仅)测试期间关闭标准文件描述符:

$ test -f /dev/stdout <&- >&- 2>&-
$ echo $?
1

关于linux - 如何使用 bash 写入除现有常规文件以外的任何文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203566/

相关文章:

c - 如何使用U-Boot将应用加载到板子上

linux - screen self 删除

linux - tar :cannot stat : No such file or directory when shell script run

bash - Docker Ubuntu 环境变量

bash - 使用 sed/awk 删除多余的行

linux - 终端输出异常

python - 未绑定(bind)本地错误 : local variable 'W' referenced before assignment

php - 简单代码 - 不输出消息

swift - NSUserUnixTask 悄悄忽略脚本

C-伪shell和并发