Overwrite file only if databash_history: comment out dangerous commands: `#`Capturing data from a Fluke 1620a via Bash /dev/tcp file descriptorHow to use output redirection dynamically?How to upload a file and then check it and run some other commands using only ssh, cat, and diff in a single SSH session?Detect pushd depth in bash?When processing input files is making copies/updating and renaming a valid approach?How to make any program work with the tee command?Redirection and piping for greppingReplacing Line if it Matches Line from Other File in Nested [While, IF, Sed] Statement

Does adding the 'precise' tag to daggers break anything?

How does the government purchase things?

Can my boyfriend, who lives in the UK and has a Polish passport, visit me in the USA?

Importing ES6 module in LWC project (sfdx)

How to avoid using System.String with Rfc2898DeriveBytes in C#

Why don't politicians push for fossil fuel reduction by pointing out their scarcity?

Is there a known non-euclidean geometry where two concentric circles of different radii can intersect? (as in the novel "The Universe Between")

Metal that glows when near pieces of itself

Vacuum collapse -- why do strong metals implode but glass doesn't?

What is "Wayfinder's Guide to Eberron"?

Why is 日本 read as "nihon" but not "nitsuhon"?

Why doesn't mathematics collapse even though humans quite often make mistakes in their proofs?

To "hit home" in German

In an emergency, how do I find and share my position?

Are there reliable, formulaic ways to form chords on the guitar?

Don't understand MOSFET as amplifier

Was this pillow joke on Friends intentional or a mistake?

Running script line by line automatically yet being asked before each line from second line onwards

Does Git delete empty folders?

Defense against attacks using dictionaries

Co-author responds to email by mistake cc'ing the EiC

Can I submit a paper under an alias so as to avoid trouble in my country?

Is "stainless" a bulk or a surface property of stainless steel?

How can I run SQL Server Vulnerability Assessment from a SQL Job?



Overwrite file only if data


bash_history: comment out dangerous commands: `#`Capturing data from a Fluke 1620a via Bash /dev/tcp file descriptorHow to use output redirection dynamically?How to upload a file and then check it and run some other commands using only ssh, cat, and diff in a single SSH session?Detect pushd depth in bash?When processing input files is making copies/updating and renaming a valid approach?How to make any program work with the tee command?Redirection and piping for greppingReplacing Line if it Matches Line from Other File in Nested [While, IF, Sed] Statement






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I am trying to overwrite a file with command output, but only if there is any output. That is, I usually want



mycommand > myfile


but if this would overwrite myfile with empty data, I wish to retain the old version of myfile. I thought that something using ifne should be possible, a la



mycommand | ifne (cat > myfile) 


but that does not work ...



An indirect approach



mycommand | tee mytempfile | ifne mv mytempfile myfile


works, but I consider the use of that temp file unelegant.



Q: Why does my first idea not work? Can it be made work? Or is there another nice and perhaps completely different solution for my original problem?










share|improve this question



















  • 3





    "Redirecting to a separate file, checking the size of that file and possibly renaming it" seems pretty straight-forward to me. Why not use a temporary file?

    – Jeff Schaller
    8 hours ago

















1















I am trying to overwrite a file with command output, but only if there is any output. That is, I usually want



mycommand > myfile


but if this would overwrite myfile with empty data, I wish to retain the old version of myfile. I thought that something using ifne should be possible, a la



mycommand | ifne (cat > myfile) 


but that does not work ...



An indirect approach



mycommand | tee mytempfile | ifne mv mytempfile myfile


works, but I consider the use of that temp file unelegant.



Q: Why does my first idea not work? Can it be made work? Or is there another nice and perhaps completely different solution for my original problem?










share|improve this question



















  • 3





    "Redirecting to a separate file, checking the size of that file and possibly renaming it" seems pretty straight-forward to me. Why not use a temporary file?

    – Jeff Schaller
    8 hours ago













1












1








1








I am trying to overwrite a file with command output, but only if there is any output. That is, I usually want



mycommand > myfile


but if this would overwrite myfile with empty data, I wish to retain the old version of myfile. I thought that something using ifne should be possible, a la



mycommand | ifne (cat > myfile) 


but that does not work ...



An indirect approach



mycommand | tee mytempfile | ifne mv mytempfile myfile


works, but I consider the use of that temp file unelegant.



Q: Why does my first idea not work? Can it be made work? Or is there another nice and perhaps completely different solution for my original problem?










share|improve this question














I am trying to overwrite a file with command output, but only if there is any output. That is, I usually want



mycommand > myfile


but if this would overwrite myfile with empty data, I wish to retain the old version of myfile. I thought that something using ifne should be possible, a la



mycommand | ifne (cat > myfile) 


but that does not work ...



An indirect approach



mycommand | tee mytempfile | ifne mv mytempfile myfile


works, but I consider the use of that temp file unelegant.



Q: Why does my first idea not work? Can it be made work? Or is there another nice and perhaps completely different solution for my original problem?







bash






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 8 hours ago









Hagen von EitzenHagen von Eitzen

1085 bronze badges




1085 bronze badges










  • 3





    "Redirecting to a separate file, checking the size of that file and possibly renaming it" seems pretty straight-forward to me. Why not use a temporary file?

    – Jeff Schaller
    8 hours ago












  • 3





    "Redirecting to a separate file, checking the size of that file and possibly renaming it" seems pretty straight-forward to me. Why not use a temporary file?

    – Jeff Schaller
    8 hours ago







3




3





"Redirecting to a separate file, checking the size of that file and possibly renaming it" seems pretty straight-forward to me. Why not use a temporary file?

– Jeff Schaller
8 hours ago





"Redirecting to a separate file, checking the size of that file and possibly renaming it" seems pretty straight-forward to me. Why not use a temporary file?

– Jeff Schaller
8 hours ago










2 Answers
2






active

oldest

votes


















6














Your first approach works, you just need to give a command to ifne (see man ifne):



NAME
ifne - Run command if the standard input is not empty

SYNOPSIS
ifne [-n] command

DESCRIPTION
ifne runs the following command if and only if the standard input is
not empty.


So you need to give it a command to run. You're almost there, tee will work:



command | ifne tee myfile > /dev/null


If your command doesn't produce an enormous amount of data, if it's small enough to fit in a variable, you can also do:



var=$(mycommand)
[[ -n $var ]] && printf '%sn' "$var" > myfile





share|improve this answer


































    4














    The pedestrian solution:



    tmpfile=$(mktemp)

    mycommand >"$tmpfile"
    if [ -s "$tmpfile" ]; then
    cat "$tmpfile" >myfile
    fi

    rm -f "$tmpfile"


    That is, save the output to a temporary file, then test whether it's empty or not. If it's not empty, copy its contents over your file. In the end, delete the temporary file.



    I'm using cat "$tmpfile" >myfile rather than cp "$tmpfile" myfile (or mv) to get the same effect as you would have gotten from mycommand >myfile, i.e. to truncate the existing file and preserve ownership and permissions.



    If $TMPDIR (used by mktemp) is on a memory-mounted filesystem, then this would not write to disk other than possibly when writing to myfile. It would additionally be more portable than using ifne.






    share|improve this answer





























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "106"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f536490%2foverwrite-file-only-if-data%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      6














      Your first approach works, you just need to give a command to ifne (see man ifne):



      NAME
      ifne - Run command if the standard input is not empty

      SYNOPSIS
      ifne [-n] command

      DESCRIPTION
      ifne runs the following command if and only if the standard input is
      not empty.


      So you need to give it a command to run. You're almost there, tee will work:



      command | ifne tee myfile > /dev/null


      If your command doesn't produce an enormous amount of data, if it's small enough to fit in a variable, you can also do:



      var=$(mycommand)
      [[ -n $var ]] && printf '%sn' "$var" > myfile





      share|improve this answer































        6














        Your first approach works, you just need to give a command to ifne (see man ifne):



        NAME
        ifne - Run command if the standard input is not empty

        SYNOPSIS
        ifne [-n] command

        DESCRIPTION
        ifne runs the following command if and only if the standard input is
        not empty.


        So you need to give it a command to run. You're almost there, tee will work:



        command | ifne tee myfile > /dev/null


        If your command doesn't produce an enormous amount of data, if it's small enough to fit in a variable, you can also do:



        var=$(mycommand)
        [[ -n $var ]] && printf '%sn' "$var" > myfile





        share|improve this answer





























          6












          6








          6







          Your first approach works, you just need to give a command to ifne (see man ifne):



          NAME
          ifne - Run command if the standard input is not empty

          SYNOPSIS
          ifne [-n] command

          DESCRIPTION
          ifne runs the following command if and only if the standard input is
          not empty.


          So you need to give it a command to run. You're almost there, tee will work:



          command | ifne tee myfile > /dev/null


          If your command doesn't produce an enormous amount of data, if it's small enough to fit in a variable, you can also do:



          var=$(mycommand)
          [[ -n $var ]] && printf '%sn' "$var" > myfile





          share|improve this answer















          Your first approach works, you just need to give a command to ifne (see man ifne):



          NAME
          ifne - Run command if the standard input is not empty

          SYNOPSIS
          ifne [-n] command

          DESCRIPTION
          ifne runs the following command if and only if the standard input is
          not empty.


          So you need to give it a command to run. You're almost there, tee will work:



          command | ifne tee myfile > /dev/null


          If your command doesn't produce an enormous amount of data, if it's small enough to fit in a variable, you can also do:



          var=$(mycommand)
          [[ -n $var ]] && printf '%sn' "$var" > myfile






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 7 hours ago









          ilkkachu

          67.2k10 gold badges112 silver badges193 bronze badges




          67.2k10 gold badges112 silver badges193 bronze badges










          answered 8 hours ago









          terdonterdon

          141k34 gold badges289 silver badges467 bronze badges




          141k34 gold badges289 silver badges467 bronze badges


























              4














              The pedestrian solution:



              tmpfile=$(mktemp)

              mycommand >"$tmpfile"
              if [ -s "$tmpfile" ]; then
              cat "$tmpfile" >myfile
              fi

              rm -f "$tmpfile"


              That is, save the output to a temporary file, then test whether it's empty or not. If it's not empty, copy its contents over your file. In the end, delete the temporary file.



              I'm using cat "$tmpfile" >myfile rather than cp "$tmpfile" myfile (or mv) to get the same effect as you would have gotten from mycommand >myfile, i.e. to truncate the existing file and preserve ownership and permissions.



              If $TMPDIR (used by mktemp) is on a memory-mounted filesystem, then this would not write to disk other than possibly when writing to myfile. It would additionally be more portable than using ifne.






              share|improve this answer































                4














                The pedestrian solution:



                tmpfile=$(mktemp)

                mycommand >"$tmpfile"
                if [ -s "$tmpfile" ]; then
                cat "$tmpfile" >myfile
                fi

                rm -f "$tmpfile"


                That is, save the output to a temporary file, then test whether it's empty or not. If it's not empty, copy its contents over your file. In the end, delete the temporary file.



                I'm using cat "$tmpfile" >myfile rather than cp "$tmpfile" myfile (or mv) to get the same effect as you would have gotten from mycommand >myfile, i.e. to truncate the existing file and preserve ownership and permissions.



                If $TMPDIR (used by mktemp) is on a memory-mounted filesystem, then this would not write to disk other than possibly when writing to myfile. It would additionally be more portable than using ifne.






                share|improve this answer





























                  4












                  4








                  4







                  The pedestrian solution:



                  tmpfile=$(mktemp)

                  mycommand >"$tmpfile"
                  if [ -s "$tmpfile" ]; then
                  cat "$tmpfile" >myfile
                  fi

                  rm -f "$tmpfile"


                  That is, save the output to a temporary file, then test whether it's empty or not. If it's not empty, copy its contents over your file. In the end, delete the temporary file.



                  I'm using cat "$tmpfile" >myfile rather than cp "$tmpfile" myfile (or mv) to get the same effect as you would have gotten from mycommand >myfile, i.e. to truncate the existing file and preserve ownership and permissions.



                  If $TMPDIR (used by mktemp) is on a memory-mounted filesystem, then this would not write to disk other than possibly when writing to myfile. It would additionally be more portable than using ifne.






                  share|improve this answer















                  The pedestrian solution:



                  tmpfile=$(mktemp)

                  mycommand >"$tmpfile"
                  if [ -s "$tmpfile" ]; then
                  cat "$tmpfile" >myfile
                  fi

                  rm -f "$tmpfile"


                  That is, save the output to a temporary file, then test whether it's empty or not. If it's not empty, copy its contents over your file. In the end, delete the temporary file.



                  I'm using cat "$tmpfile" >myfile rather than cp "$tmpfile" myfile (or mv) to get the same effect as you would have gotten from mycommand >myfile, i.e. to truncate the existing file and preserve ownership and permissions.



                  If $TMPDIR (used by mktemp) is on a memory-mounted filesystem, then this would not write to disk other than possibly when writing to myfile. It would additionally be more portable than using ifne.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 5 hours ago

























                  answered 8 hours ago









                  KusalanandaKusalananda

                  160k18 gold badges316 silver badges503 bronze badges




                  160k18 gold badges316 silver badges503 bronze badges






























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Unix & Linux Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f536490%2foverwrite-file-only-if-data%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480