here 文件 (LCTT 譯註:here 文件又稱作 heredoc )不是什麼特殊的東西,只是一種 I/O 重定向方式,它告訴 bash shell 從當前源讀取輸入,直到讀取到只有分隔符的行。
這對於向 ftp、cat、echo、ssh 和許多其他有用的 Linux/Unix 命令提供指令很有用。 此功能適用於 bash 也適用於 Bourne、Korn、POSIX 這三種 shell。
語法是:
command <<EOFcmd1cmd2 arg1EOF
或者允許 shell 指令碼中的 here 文件使用 EOF<<-
以自然的方式縮排:
command <<-EOF msg1 msg2 $var on line EOF
或者
command <<'EOF' cmd1 cmd2 arg1 $var won't expand as parameter substitution turned off by single quotingEOF
或者 重定向並將其覆蓋 到名為 my_output_file.txt
的檔案中:
command <<EOF > my_output_file.txt mesg1 msg2 msg3 $var on $fooEOF
或重定向並將其追加到名為 my_output_file.txt
的檔案中:
command <<EOF >> my_output_file.txt mesg1 msg2 msg3 $var on $fooEOF
以下指令碼將所需內容寫入名為 /tmp/output.txt
的檔案中:
#!/bin/bashOUT=/tmp/output.txtecho "Starting my script..."echo "Doing something..."cat <<EOF >$OUT Status of backup as on $(date) Backing up files $HOME and /etc/EOFecho "Starting backup using rsync..."
你可以使用cat命令檢視/tmp/output.txt檔案:
$ cat /tmp/output.txt
範例輸出:
Status of backup as on Thu Nov 16 17:00:21 IST 2017 Backing up files /home/vivek and /etc/
像 $HOME
這類變數和像 $(date)
這類命令在指令碼中會被解釋為替換。 要禁用它,請使用帶有 'EOF'
這樣帶有單引號的形式,如下所示:
#!/bin/bashOUT=/tmp/output.txtecho "Starting my script..."echo "Doing something..."# No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. # If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document # are not expanded. So EOF is quoted as followscat <<'EOF' >$OUT Status of backup as on $(date) Backing up files $HOME and /etc/EOFecho "Starting backup using rsync..."
你可以使用 cat 命令檢視 /tmp/output.txt
檔案:
$ cat /tmp/output.txt
範例輸出:
Status of backup as on $(date) Backing up files $HOME and /etc/
語法是:
tee /tmp/filename <<EOF >/dev/nullline 1line 2line 3$(cmd)$var on $fooEOF
或者通過在單引號中參照 EOF
來禁用變數替換和命令替換:
tee /tmp/filename <<'EOF' >/dev/nullline 1line 2line 3$(cmd)$var on $fooEOF
這是我更新的指令碼:
#!/bin/bashOUT=/tmp/output.txtecho "Starting my script..."echo "Doing something..."tee $OUT <<EOF >/dev/null Status of backup as on $(date) Backing up files $HOME and /etc/EOFecho "Starting backup using rsync..."
這是我更新的指令碼:
#!/bin/bashOUT=/tmp/output.txt## in memory here docs ## thanks https://twitter.com/freebsdfrauexec 9<<EOF Status of backup as on $(date) Backing up files $HOME and /etc/EOF## continueecho "Starting my script..."echo "Doing something..."## do itcat <&9 >$OUTecho "Starting backup using rsync..."