如何在 PS1 變數中插入 bash 腳本

如何在 PS1 變數中插入 bash 腳本

我製作了一個自訂 PS1 變量,這非常令人困惑。這是最接近完全正常工作的一個:

PS1="\n[\e[1;31m]\u@\H[\e[35m] \@ [\e[32m] PWD: \w [\e[1;34m]此資料夾有\$ ( /bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') 檔案 [\e[1;33m] 總共 \$(/bin/ls -lah | / bin/grep -m 1 總計| /bin/sed 's/total //')b\n`if [ \$? = 0 ]; 然後echo [\e[32m]^_^ [\e[0m ]有效- [\e[0m]; else echo [\e[31m]O_O[\e[0m]無效- fi`"

這與前面的程式碼範例是相同的程式碼,但它已被分成區塊並添加了註解以提高可讀性:

#User@Host [Red]
\n\[\e[1;31m\]\u@\H

#Hour [Purple]
\[\e[35m\] \@ 

#PWD [Green]
\[\e[32m\] PWD: \w 

#Number of files in PWD [Blue]
\[\e[1;34m\]This folder has \$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files 

#Amount of space the PWD files take, also line break [Yellow]
\[\e[1;33m\]A total of \$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed 's/total //')b\n

#Malfunctioning condition, should smile if the instruction went right, or poker-face if not [green and red]
\`if [ \$? = 0 ]; then echo \[\e[32m\]^_^ \[\e[0m\]\[\e[0m\]Worked - \[\e[0m\]; else echo \[\e[31m\]O_O\[\e[0m\] Didn't worked - ; fi\`

試圖解釋這個問題:

  • if尋找執行 for (例如) 後不再為 false 的條件"This folder has \$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed 's: ::g') files",因為如果最新語句有一個乾淨的結尾,則該條件為 true。

我怎樣才能讓它工作,同時將輸出保持在同一位置?如果將 if 移至第一個命令執行之前,則效果很好。

我想if在 PS1 的開頭分配一個具有該條件的變數。然後if在這個位置上的其他人會判斷不會改變的替代變數。但不幸的是我對 Bash 毫無技巧。我已經嘗試過一千次左右,但都沒有成功。

像這樣的東西(但寫得很好):

PS1="`if [ \$? = 0 ];then echo "prev_err=0"; else prev_err=0; fi\` 
...[Some more code in between]...
`if [ \$prev_err = 0 ]
    then echo "No error"
    else echo "There was an error in the statement." 
fi\`"

某些`(反引號字元)位於錯誤的位置或在前面的程式碼區塊中被省略。

答案1

您最好在 PROMPT_COMMAND 中執行大部分操作,引用 Bash 手冊“如果設置,則在發出每個主提示之前將值作為命令執行”

也可以看看這個巨大的例子

我的是 :-

PROMPT_COMMAND='history -a; history -n; printf "\e]1;${PWD}\a"'

這使我的歷史記錄在終端機視窗之間保持同步。

那麼你應該在 bash 函數中放入盡可能多的內容來簡化問題。

順便說一句 - 您可能會發現比僅僅獲取文件使用情況du -sh .更有用、更容易一些。/bin/ls -lah | /bin/grep -m 1 total

答案2

我的提示包含幾個函數,例如

PS1='$(exit_code=$?; [[ $exit_code -eq 0 ]] || printf %s \[$BOLD_FORMAT\] \[$ERROR_FORMAT\] $exit_code \[$RESET_FORMAT\] " ")'

那對你有用嗎?

相關內容