簡體   English   中英

下面的 bash 命令是什么意思?

[英]What does the following bash command mean?

命令-

(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -)

文檔中如何解釋此命令-

(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -)
# Move entire file tree from one directory to another
# [courtesy Alan Cox <a.cox@swansea.ac.uk>, with a minor change]

# 1) cd /source/directory
#    Source directory, where the files to be moved are.
# 2) &&
#   "And-list": if the 'cd' operation successful,
#    then execute the next command.
# 3) tar cf - .
#    The 'c' option 'tar' archiving command creates a new archive,
#    the 'f' (file) option, followed by '-' designates the target file
#    as stdout, and do it in current directory tree ('.').
# 4) |
#    Piped to ...
# 5) ( ... )
#    a subshell
# 6) cd /dest/directory
#    Change to the destination directory.
# 7) &&
#   "And-list", as above
# 8) tar xpvf -
#    Unarchive ('x'), preserve ownership and file permissions ('p'),
#    and send verbose messages to stdout ('v'),
#    reading data from stdin ('f' followed by '-').
#
#    Note that 'x' is a command, and 'p', 'v', 'f' are options.
#
# Whew!

在上面給出的解釋中有幾件事我不明白 -

  • 在第三步中,它聲明f -將目標文件指定為標准輸出,但 output 現在沒有任何內容,在創建存檔時,從哪里提供文件名?
  • 在它聲明的第 8 步中,它從標准輸入讀取數據,但我沒有提供任何輸入,stream 中是否還有任何輸入?

這個命令工作正常,但我對它的工作原理有點困惑。 任何幫助都會有所幫助。

編輯-指向此的鏈接,向下滾動一下您會找到它。

您從代碼中引用的解釋非常好。 我希望我讀過(或寫過)的每一個劇本都被記錄得這么好。

在第三步中,它聲明f -將目標文件指定為標准輸出,但 output 現在沒有任何內容,在創建存檔時,從哪里提供文件名?

沒有文件名。 歸檔數據被寫入標准輸出,進程的標准 output stream。 如果它沒有通過管道傳輸到另一個程序中,那么它將顯示在屏幕上。

在它聲明的第 8 步中,它從標准輸入讀取數據,但我沒有提供任何輸入,stream 中是否還有任何輸入?

如文檔第 4 步所述,第一個tar命令的 output(到其標准輸出)通過管道傳輸到第二個tar命令(的標准輸入)。 不能直接給第二個tar任何輸入,因為它是從 pipe 讀取其輸入,而不是鍵盤或任何常規文件。

在第 3 步中,它聲明 f - 將目標文件指定為標准輸出,但 output 現在沒有任何內容,在創建存檔時,從哪里提供文件名?

stdinstdout是操作系統為每個進程(運行的命令)創建的兩個數據流。 該過程可能會或可能不會使用這些流,但操作系統無論如何都會創建它們。

這是第一個進程將其 output 寫入的地方。

內存中的數據流不需要有文件名,這些不是磁盤上的常規文件。

在它聲明的第 8 步中,它從標准輸入讀取數據,但我沒有提供任何輸入,stream 中是否還有任何輸入?

有 2 個進程由 pipe |分隔您可以將其可視化為:

(cd /source/directory && tar cf - . ) -> [stdout] -> | -> [stdin] -> (cd /dest/directory && tar xpvf -)

因此,左側的第一個進程將 output 寫入其自己的stdout pipe | 是操作系統級別的管道,它將數據從前一個進程的標准stdout泵送到下一個進程的stdin 右側的進程從其stdin讀取數據。

此外,像 pipe | 模式,破折號-是提供代替文件的常見 cli 模式,它告訴命令從stdin/stdout而不是文件讀取寫入數據。

第一個括號執行以下操作:它將目錄更改為/source/directory/並生成一個 tar 文件,其內容是當前目錄“。” 並將其發送到標准 output。

第二個括號將目錄更改為/dest/directory/並從那里提取它從標准輸入中讀取的存檔。

即你解壓“/source/directory”的內容,然后在“/dest/directory”中解壓它,而不使用中間文件,只需一個pipe “|” 在兩個命令之間建立連接。

注意:括號創建一個子進程,所以你有一個子進程執行tar c和另一個執行tar f同時運行,一個子進程的 output 被饋送到第二個子進程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM