Bash

顯示控制台輸出下面的 1 行或多行

  • January 5, 2018

當我執行tail ~/SOMEFILE我得到的命令時,例如:

testenv@vps_1:~# tail ~/SOMEFILE
   This is the content of SOMEFILE.

testenv@vps_1:~#但是如果我想在:和輸出之間有一個輸入怎麼辦:This is the content of SOMEFILE.

所以最終的結果是這樣的:

testenv@vps_1:~# tail ~/SOMEFILE

   This is the content of SOMEFILE.

或這個:

testenv@vps_1:~# tail ~/SOMEFILE


   This is the content of SOMEFILE.

或這個:

testenv@vps_1:~# tail ~/SOMEFILE



   This is the content of SOMEFILE.

注意:第一個範例顯示兩部分之間的一行間距,第二個範例顯示兩行,第三個範例顯示三行。

有沒有辦法確保tail像我在範例中所示的那樣,在 Bash 中,僅針對這個特定命令(當然不是所有命令),該問題的輸出(或任何其他輸出)會被間隔開?

最簡單的選擇是手動列印那些額外的換行符,例如:

printf '\n\n\n'; tail ~/SOMEFILE

但如果你想:

  • 這樣做只是為了tail
  • 不要在每次tail呼叫時編寫額外的命令
  • 簡單而全面地控制換行符的數量

那麼我建議你在你的 aliases/rc 文件中添加一個函式。

例如:

# Bash version

# In Bash we can override commands with functions
# thanks to the `command` builtin
tail() {

 # `local` limit the scope of variables,
 # so we don't accidentally override global variables (if any).
 local i lines

 # `lines` gets the value of the first positional parameter.
 lines="$1"

 # A C-like iterator to print newlines.
 for ((i=1; i<=lines; i++)); do
   printf '\n'
 done

 # - `command` is a bash builtin, we can use it to run a command.
 #   whose name is the same as our function, so we don't trigger
 #   a fork bomb: <https://en.wikipedia.org/wiki/Fork_bomb>
 #
 # - "${@:2}" is to get the rest of the positional parameters.
 #   If you want, you can rewrite this as:
 #
 #       # `shift` literally shifts the positional parameters
 #       shift
 #       command "${@}"
 #
 #   to avoid using "${@:2}"
 command tail "${@:2}"

}

#===============================================================================

# POSIX version

# POSIX standard does not demand the `command` builtin,
# so we cannot override `tail`.
new_tail() {

 # `lines` gets the value of the first positional parameter.
 lines="$1"

 # `i=1`, `[ "$i" -le "$lines" ]` and `i=$((i + 1))` are the POSIX-compliant
 # equivalents to our C-like iterator in Bash
 i=1
 while [ "$i" -le "$lines" ]; do
   printf '\n'
   i=$((i + 1))
 done

 # Basically the same as Bash version
 shift
 tail "${@}"

}

因此,您可以將其稱為:

tail 3 ~/SOMEFILE

tail沒有任何論據來管理這個。

作為一種解決方法,您可以做的是在執行 tail 命令之前列印一個空行。

echo && tail ~/SOMEFILE

對於多行yes也可以使用命令。是的,這裡建議的手冊頁: bash: print x number of blank lines

yes '' | sed 5q && tail ~/SOMEFILE

將 5 替換為所需的空行數。

注意:您可能還想看看編輯終端提示。但隨後它將是終端範圍的,並且不僅與您的特定命令相關聯。

引用自:https://unix.stackexchange.com/questions/412240