5

我有一個bash腳本中,我想傳達給對標準輸出的用戶,而且還通過文件描述符發送到一個子進程的命令 - 是這樣的:文件描述符權限被bash進程替換拒絕?

# ... 
# ... 

echo "Hello user, behold a cleared gnuplot window" 

# pass the string "clear" to gnuplot via file descriptor 3 
echo "clear" >&3 

所以我想我可以「此設置」首先開始像這樣子:

#!/bin/bash 

# Initiate(?) file descriptor 3, and let it direct to a newly 
# started gnuplot process: 
exec >3 >(gnuplot) 

但是,這會產生錯誤:

/dev/fd/63: Permission denied 

是個是預期的嗎?

我不明白髮生了什麼事。 (我是否做錯了什麼?是否我的系統有一些特殊的安全設置,不允許我在做什麼?(運行Ubuntu Linux 12.10。))

「解決方法」 - 看起來如下等同用什麼,我試圖做的,和工作沒有錯誤:

#!/bin/bash 

# open fd 3 and direct to where fd 1 directs to, i.e. std-out 
exec 3>&1 

# let fd 1 direct to a newly opened gnuplot process 
exec 1> >(gnuplot) 

# fd 1 now directs to the gnuplot process, and fd 3 directs to std-out. 
# I would like it the other way around. So we'll just swap fd 1 and 3 
# (using an extra file descriptor, fd 4, as an intermediary) 

exec 4>&1 # let fd 4 direct to wherever fd 1 directs to (the gnuplot process) 
exec 1>&3 # let fd 1 direct to std-out 
exec 3>&4 # let fd 3 direct to the gnuplot process 
exec 4>&- # close fd 4 

或者像一個班輪:

#!/bin/bash 
exec 3>&1 1> >(gnuplot) 4>&1 1>&3 3>&4 4>&- 

爲什麼這個工作,但最初的版本是不是?

任何幫助非常感謝。

$ bash --version 
GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu) 
[...] 

回答

1

你有一個錯字;使用exec 3> >(gnuplot)而不是exec >3 >(gnuplot)

順便說一句,是的,它的預期。 exec >3 >(gnuplot)將stdout重定向到名爲3的文件,然後嘗試執行>(gnuplot)(轉換爲/ dev/fd/63)作爲程序。

1

我得到:

/dev/fd/63: Permission denied

應有的注意here使用sudo的進程替換。

所以做到這一點:

$ sudo ruby <(echo "puts 'foo'") 
ruby: Bad file descriptor -- /dev/fd/63 (LoadError) 
+0

嘗試'-C'標誌。 – Tobu

+0

man sudo ...「-C(關閉)選項允許用戶指定高於標準錯誤的起始點(文件描述符三)。」那麼我如何在上述情況下使用它? –