Search code examples
bashoutputhiddenhidden-files

Is there a way to save output from bash commands to a "file/variable" in bash without creating a file in your directory


I'm writing commands that do something like ./script > output.txt so that I can use the files in later scripts like ./script2 output.txt otherFile.txt > output2.txt. I remove them all at the end of the script, but when I'm testing certain things or debugging it's tricky to search through all my sub directories and files which have been created in the script. Is the best option just to create a hidden file?


Solution

  • As always, there are numerous ways to do so. If you want to avoid files altogether, you can save the output (STDOUT) of a command in a variable and pass it to the next command as a file using the <() operator:

    output=$(cat /usr/include/stdio.h)
    cat <(echo "$output")
    

    Alternatively, you can do so in a single command line:

    cat <(cat /usr/include/stdio.h)
    

    This assumes that the next command strictly requires a file for input.

    I tend to avoid temporary files whenever possible to eliminate the need for a cleanup step that gets executed in all cases unless large amounts of data have to be processed.