可讀別名我知道如何使一個文件描述符如何使一個文件描述符
exec 3>&1 1> /dev/null
echo "hello world" >&3
的別名,但這不是可讀。有沒有辦法讓它可讀?(而不是>我可以寫LOG或INFO或DEBUG)嗎?
可讀別名我知道如何使一個文件描述符如何使一個文件描述符
exec 3>&1 1> /dev/null
echo "hello world" >&3
的別名,但這不是可讀。有沒有辦法讓它可讀?(而不是>我可以寫LOG或INFO或DEBUG)嗎?
您可以簡單地使用參數存儲要使用的文件描述符。
exec 3>&1 1>/dev/null
LOG=3
echo "hello world" >&$LOG
您不能>&
部分存儲在一個參數,因爲這是shell語法,而不是數據。但是,您可以編寫一個將其參數輸出到特定文件描述符的函數。
LOG() {
echo "[email protected]" >&3
}
LOG "hello world"
如果您編寫&1
,請參閱標準輸出,它用於輸出。您還使用>
進行輸出的重定向。
如果您關心的是輸入,您可以參考&0
例如使用標準輸入。在這種情況下,您還應該使用<
進行輸入。
例如:
exec 3<&0
欲瞭解更多信息類型man bash
,然後查看重定向的部分。
我不明白你爲什麼要FD 3. 在我的解決方案,我告訴你如何可以混合區FD1和FD3:
function opendebug {
exec 3>&1 1> /dev/null
}
function mylog {
level=$1
shift
printf "(fd 1) %s: %s\n" "${level}" "$*"
printf "(fd 3) %s: %s\n" "${level}" "$*" >&3
}
function logerror {
if [ ${loglevel} -ge 1 ]; then
mylog "ERROR" "$*"
fi
}
function loginfo {
if [ ${loglevel} -ge 3 ]; then
mylog "INFO" "$*"
fi
}
function logdebug {
if [ ${loglevel} -ge 5 ]; then
mylog "DEBUG" "$*"
fi
}
export loglevel=3
logerror "Line with error"
loginfo "Line with info"
logdebug "Line with debug" # will be suppressed
echo Open debug
opendebug
logerror "Line with error"
loginfo "Line with info"
logdebug "Line with debug" # will be suppressed
輸出:
(fd 1) ERROR: Line with error
(fd 1) INFO: Line with info
Open debug
(fd 3) ERROR: Line with error
(fd 3) INFO: Line with info