簡體   English   中英

從bash的提示符寫入輸出文件

[英]Writing into output file from prompt in bash

我一直在研究一些腳本,並制作了一個簡單的簡短快照,並希望分享以查看是否有人可以提供幫助。 我基本上是使用提示符執行腳本。 第一個提示會問我是否要繼續,這很好,第二個提示會問我是否要將我的輸出寫到txt文件中,這也很好。 但是我的問題是,當我點擊“是”時,是否有辦法告訴腳本以某種方式將輸出寫入txt文件,但是更有可能是否有一種方法而不必復制命令? 我知道我可以將所有命令都寫到輸出提示中,並根據是否按是或否來寫或跳過寫。

#!/bin/bash

# Disclaimer
read -p "[Y] for Yes or [N] for GTFO: " prompt
if [[ $prompt == "y" ||  $prompt == "" ]]
then

# Output save
read -p "[Y] to save output to txt [N] don't save: " prompt
if [[ $prompt == "y" ||  $prompt == "" ]]
then
    touch /root/Desktop info.txt
    ifconfig >> /root/Desktop info.txt

fi
printf "\n"
    printf "Executing script, and will scan the system for information \n"
sleep 1.4
printf "\n"

# Will Check for IP
printf "IP Addresses: \n"
ifconfig

else
    printf "\n"
    printf "Exiting, Bye \n"

fi

如果只在用戶要求時才將腳本的輸出記錄到文件中,則可以執行以下操作:

if [[ $prompt == "y" ||  $prompt == "" ]]
then
    trap 'rm $fifo' 0 
    fifo=$(mktemp)
    rm $fifo
    mkfifo $fifo
    tee output-of-script < $fifo &
    exec > $fifo  # All output of any command run will now go to the fifo,
                  # which will be read by tee
fi

允許用戶指定輸出文件名而不是對文件“ output-of-script”進行硬編碼可能會更清潔,我強烈建議您不要進行提示。 將這種事情指定為命令行參數要干凈得多。

當然,如果您不想將輸出復制到當前的stdout和文件中,則這要簡單得多:

if ...; then exec > output-file; fi

將導致所有后續命令的輸出被寫入output-file

另外,如果您使用的是bash,則運行tee也會更簡單:

if ...; then exec > >(tee output-file); fi

暫無
暫無

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

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