文字編輯器heredoc的用法

2021-10-14 13:29:19 字數 2578 閱讀 9961

在 linux 和 unix 的 shell 中有乙個不為人知的功能,它能讓你用 cat 命令開啟乙個 do-while 迴圈。它被稱為 heredoc,無論你使用什麼 shell,它都能讓你或多或少地擁有乙個文字編輯器。

heredoc的語法是:

$ cat << eof >> example.txt
中間的字串(eof),本質上是乙個停止迴圈的條件。也就是說,如果你在一行中單獨輸入它,迴圈就會結束。在迴圈過程中,無論你在終端中輸入什麼,都會被管道傳送到目標檔案中(在本例中)。

安裝

只要你有乙個終端,你就能夠啟動 heredoc。我在 bash、tsh 和 korn shell 中使用過這個語法技巧。

使用 heredoc

要開啟乙個 heredoc 「會話」,你可以使用帶重定向的cat命令。首先用終止字串(常見約定是eof,代表 「end of file」,但它實際上可以是任何字串)指向cat命令。在終止字串之後,將輸出重定向到乙個目標檔案。然後,你就可以直接在終端中輸入了,可以使用最常見的 shell 鍵盤快捷鍵來處理你的工作。當你在一行上輸入你指定的終止字串時,你的會話就結束了。你可以通過唯一的提示符(通常是>)知道你是在乙個 heredoc 迴圈中。

$ cat << eof >> example.txt

> everything you type here will be placed into example.txt when i type eof on a line by itself. until then, you can type...

>

> whatever...

>

> you want to type.

>

> eof

$

在終端等待 eof 時,你輸入的所有內容都會被放入目標檔案中,提示符被忽略,eof 本身也不是檔案的一部分。

everything you type here will be placed into example.txt when i type eof on a line by itself. until then, you can type...

whatever...

you want to type.

在現實中,你可能不會用 heredoc 語法來代替乙個正常的文字編輯器。它是乙個很好的快速處理方式,可以輸入多行,但超過 10 行左右就開始限制它的作用了。例如,如果不觸發你 shell 的 history 功能,你就不能編輯以前的行。根據你的 shell 和配置,你可能需要先按向上鍵,然後按向下鍵來找回你的文字,然後用ctrl+b來後退。

你的 shell 的大部分功能都能正常工作,但可能沒有撤銷功能,也沒有什麼錯誤恢復功能。

此外,即使是最簡安裝的系統,可能也至少安裝了 vi 或 ed。

然而 heredoc 還是很有用的!它比 echo 更靈活,當你在編寫 shell 指令碼時,它是不可缺少的。例如,想象一下你正在編寫乙個安裝指令碼,以便你可以自動安裝一組自定義應用。其中乙個應用沒有生成 .dekstop 檔案,所以它不會出現在你的應用選單中。為了解決這個問題,你決定在安裝時生成乙個 .desktop 檔案。

與其編寫乙個 .desktop 檔案,然後作為安裝指令碼的外部依賴,不如在安裝指令碼中使用 heredoc:

#!/bin/sh

version=$

pkgnam=$

pkg="$"-"$"-`arch`.tgz

# download package

wget "$"

tar txvf "$"

# use here doc to create missing .desktop file

[desktop entry]

version=1.0

name="$"

comment="$"

exec="$" %f

eof 

# insert the rest of an install script...

[desktop entry]

version=1.0

name=example

comment=example

exec=example %f

正如你所看到的,你可以在 heredoc 中使用變數,而且它們得到了正確的解析。eof字串並沒有出現在檔案中,它只是標誌著 heredoc 的結束。

比 echo 更好

heredoc 技術通常被認為比 echo 或 printf 更容易,因為一旦你「進入」了文件,你就可以自由地做任何你想做的事情。從這個意義上說,它是自由的,但與合適的文字編輯器相比,它是有限的。

使用 heredoc 來做快速筆記和 shell 指令碼,再也不用為如何動態生成配置檔案而煩惱了。

文字編輯器

include stdio.h include string.h include stdlib.h define len sizeof struct linetable struct linetable main 輸出並加入行號 display struct linetable head else ...

文字編輯器

text editer文字編輯器 data ref container tec type ref to cl gui custom container.data ref edit type ref to cl gui textedit.data text line 85 work area it t...

文字編輯器

uedit notepad mybase 筆記類工具 sublime 列模式操作很牛叉 sublime 快捷鍵 常用類操作模式 1.選擇編輯的行,ctrl l,就可以操作了。2.按住shiftr 鍵盤,滑鼠右鍵選擇欲選擇內容。ctrl l 選擇整行 按住 繼續選擇下行 ctrl kk 從游標處刪除至...