0

I've been working on some script, and took a simple short snapshot out and wanted to share to see if someone could help out,. I am basically using prompt to execute my script. First prompt will ask me if I want to continue, which works fine, second prompt will ask me if I want to write my output into txt file, which works fine too. However my question is if there's a way to tell the script somehow to write the output into txt file when I hit Yes, but more likely if there's a way to do it without duplicating my commands? I know I could just write all commands into the output prompt, and depending if I hit yes or no it would write or skip writing.

#!/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

1 Answer 1

1

If you want to record the output of the script to a file only when the user requests it, you could do:

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

It's probably cleaner to allow the user to specify an output file name rather than hardcoding the file 'output-of-script', and I would strongly advise against prompting; it is much cleaner to specify this sort of thing as a command line argument.

Of course, if you don't want to duplicate output to the current stdout and the file, this is much simpler:

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

will cause the output of all subsequent commands to be written to output-file

Also, if you're using bash, running the tee can be simpler, too:

if ...; then exec > >(tee output-file); fi
Sign up to request clarification or add additional context in comments.

1 Comment

thats great! Thank you so much for the help! I like this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.