History command inside bash scriptPersistent shell argumentsCommands run when terminal is open do not appear...

How do I portray irrational anger in first person?

Would it be unbalanced to add Geas to the warlock spell list?

Why do presidential pardons exist in a country having a clear separation of powers?

Can copper pour be used as an alternative to large traces?

What's the origin of the concept of alternate dimensions/realities?

What caused the end of cybernetic implants?

Why are JWST optics not enclosed like HST?

'spazieren' - walking in a silly and affected manner?

In what language did Túrin converse with Mím?

“all of who” or “all of whom”?

How did medieval manors handle population growth? Was there room for more fields to be ploughed?

Where should I draw the line on follow up questions from previous employer

Under GDPR, can I give permission once to allow everyone to store and process my data?

Why do motor drives have multiple bus capacitors of small value capacitance instead of a single bus capacitor of large value?

What checks exist against overuse of presidential pardons in the USA?

Welche normative Autorität hat der Duden? / What's the normative authority of the Duden?

What is the following VRP?

Can UV radiation be safe for the skin?

Can authors email you PDFs of their textbook for free?

Sum and average calculator

How to save money by shopping at a variety of grocery stores?

Are sweatpants frowned upon on flights?

Necessity of tenure for lifetime academic research

Who declared the Last Alliance to be the "last" and why?



History command inside bash script


Persistent shell argumentsCommands run when terminal is open do not appear in historySome commands not working when executed via ssh while redirecting output locallyHow do I call current “.bash_history” from a script?Why a result from history command doesn't behave in a bash function?sharing or synchronizing history between Zsh and BashKeep two bash history files, one with ignoredups, one with everythingPersistent Bash history between detached processesHow can I access the history buffer in sh? (not in Bash)Hide ones command history from other users on a Linux serverFreeBSD cli history for sh shell






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







20















History is a shell-built in command I couldn't able to use that within a BASH script. So, Is there a way attain this using BASH script ?

Here we go my script for you:



#!/bin/bash
history | tail -100 > /tmp/history.log
cd /tmp
uuencode history.log history.txt | mail -s "History log of server" hello@hel.com









share|improve this question

































    20















    History is a shell-built in command I couldn't able to use that within a BASH script. So, Is there a way attain this using BASH script ?

    Here we go my script for you:



    #!/bin/bash
    history | tail -100 > /tmp/history.log
    cd /tmp
    uuencode history.log history.txt | mail -s "History log of server" hello@hel.com









    share|improve this question





























      20












      20








      20


      9






      History is a shell-built in command I couldn't able to use that within a BASH script. So, Is there a way attain this using BASH script ?

      Here we go my script for you:



      #!/bin/bash
      history | tail -100 > /tmp/history.log
      cd /tmp
      uuencode history.log history.txt | mail -s "History log of server" hello@hel.com









      share|improve this question
















      History is a shell-built in command I couldn't able to use that within a BASH script. So, Is there a way attain this using BASH script ?

      Here we go my script for you:



      #!/bin/bash
      history | tail -100 > /tmp/history.log
      cd /tmp
      uuencode history.log history.txt | mail -s "History log of server" hello@hel.com






      bash command-history scripting






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 15 at 17:40









      Rui F Ribeiro

      41.4k16 gold badges94 silver badges158 bronze badges




      41.4k16 gold badges94 silver badges158 bronze badges










      asked Jan 11 '11 at 13:54









      Vijay RamachandranVijay Ramachandran

      1011 gold badge1 silver badge4 bronze badges




      1011 gold badge1 silver badge4 bronze badges

























          8 Answers
          8






          active

          oldest

          votes


















          29















          Bash disables history in noninteractive shells by default, but you can turn it on.



          #!/bin/bash
          HISTFILE=~/.bash_history
          set -o history
          history | tail …


          But if you're trying to monitor activity on that server, the shell history is useless (it's trivial to run commands that don't show up in the history). See How can I log all process launches in Linux.



          If you're debugging a script then shell history is not the best way to get useful information. A much better tool is the debug trace facility: put set -x near the top of the script. The trace is written to standard error.






          share|improve this answer




























          • This refuses to work in a script: histtest.sh: 5: set: Illegal option -o history

            – Ken Sharp
            Jan 7 '16 at 2:56






          • 4





            @KenSharp That's because you tried to use it in an sh script (and your sh is dash juding by the exact wording of the error message). To access bash's history, you need to use bash (script starting with #!/bin/bash or #!/usr/bin/env bash).

            – Gilles
            Jan 7 '16 at 12:36






          • 1





            @KenSharp Yes it is. You obviously ran it under dash, given the error message. Bash does not have the error message Illegal option (it would say set: history: invalid option name).

            – Gilles
            Jan 7 '16 at 15:45











          • the problem with this is that it adds all commands following set -o history to the history which is then going to be stuffed up with entries like if [... vars=$(... etc.

            – nath
            Dec 18 '17 at 2:42








          • 1





            @nath That's what the question asked for. It is pretty much pointless, as I point out. Monitoring activity is a hard problem that shell history won't solve. If you're debugging a script then set -x is a lot more useful.

            – Gilles
            Dec 18 '17 at 8:19





















          6















          I'm not sure if it actually uses the history capability when running non-interactively, otherwise every shell script you run would clutter up your command history.



          Why not go directly to the source ${HOME}/.bash_history, replace history | tail -100 with tail -100 ${HOME}/.bash_history. (If you use timestamps you'd probably have to do something along the lines of grep -v ^# ${HOME}/.bash_history | tail -100).






          share|improve this answer




























          • Indeed, with timestamps, you should actually greq -v '^#[0-9]+$' (I sometimes "execute" comments in my shell...)

            – PlasmaBinturong
            Jan 18 '18 at 12:17











          • And actually, in my case, I need to use the correct history line number, but there's a difference between the output of history and the output of the grep method...

            – PlasmaBinturong
            Jan 18 '18 at 12:21











          • Ok, the fix was to synchronize the history list with the history file like this: history -a; history -c; history -r. (add, clear, read)

            – PlasmaBinturong
            Jan 18 '18 at 12:33





















          2















          If you want to use the output of the history command from an active shell session in a script, you can use an alias to run the command first. Then, in the same alias, you can call the remainder of the script. With such a configuration, you can achieve essentially the same result as having the history command in the actual script.



          For instance, you can create an alias like this, assuming the script's name is script.sh:



          alias hy_tmp='history | tail -100 > /tmp/history.log ; bash /patch/to/script.sh'


          And change the script to this:



          #!/bin/bash
          cd /tmp
          uuencode history.log history.txt | mail -s "History log of server" hello@hel.com


          I found this question while writing a process to combine, sort and synchronize ~/bash_history files on two computers so it'll be easy to search commands I've used in the past.



          It's much less of a hassle to update my cumulative history file without having to log into a new shell to have ~/bash_history updated. For monitoring a server this will obviously not work, as mentioned in the other answers.



          My usage in particular is:



          alias hbye='history | cut -c 8- > /home/chris/.bash_history_c; bash /hby.sh


          The script hby.sh then pulls all unique entries from all ~/.bash_history* files.






          share|improve this answer

































            1















            The history builtin seems to be disabled inside a shell script. See here: http://www.tldp.org/LDP/abs/html/histcommands.html



            I have not found any official documentation about this.






            share|improve this answer

































              1















              Create a script named script.sh as below. It creates a script named X and puts Y Number of lines of your history into it.



              #!/bin/bash
              SCRIPT_NAME=$1
              NUMBER_OF_LINES_BACK=$2

              # Enable History in a non interactive shell
              HISTFILE=~/.bash_history
              set -o history

              # echo shabang line and x number of lines of history to new script
              echo #!/bin/bash > $SCRIPT_NAME.sh; history | tail -n $NUMBER_OF_LINES_BACK >> $SCRIPT_NAME.sh;
              chmod u+x $SCRIPT_NAME.sh;

              # Open the newly created script with vim
              vim $SCRIPT_NAME.sh;
              ~


              Then if you want to create a script to a accomplish a task named "task" that you have been working on for the last 14 lines run



              script.sh task 14


              Then clean up your history to make a nice script!






              share|improve this answer


























              • histtest.sh: 5: set: Illegal option -o history

                – Ken Sharp
                Jan 7 '16 at 3:03





















              0















              Every user have it's own history file which is result of history command.Instead of using history command in your shell script you can use history file for user.
              There will be a .bash_history file in home directory of user, that will be the history file for the user.






              share|improve this answer

































                0















                history command is disabled by default on bash script that's why even history command won't work in .sh file. for its redirection, kindly redirect bash_history file inside the .sh file.


                or history mechanism can be enabled also by mentioning history file and change run-time parameters as mentioned below

                #!/bin/bash
                HISTFILE=~/.bash_history
                set -o history

                note: mentioned above two lines on the top of the script file. now history command will work in history.





                share|improve this answer

































                  -1















                  Short answer:



                  use history -p to perform history expansion explicitly.



                  An example follows.



                  One use case happens a lot for me is:




                  • previous command get a list of file names, and print to stdout,

                  • I need to edit those file with vim.


                  Since my bash has been set -o histexpand, usually what I did is typing



                  vim $(!!)


                  to edit those files listed by previous command.



                  Sadly sometimes mistake happens, so I enable verify by shopt -s histverify.



                  Now I can verify the expansion, with cost of one extra Return key.



                  Today I want to wrap those details into a bash function since I use them a lot,



                  function vk() {
                  set -o history && set -o histexpand;
                  vim -i ~/.viminfok $($(history -p !!));
                  }


                  Here I use two nested command substitution, the inner one to expand !! to previous command, the outer one to execute it and get the output.



                  Now I can achieve the same effect, with only three key, and one of those is Return!






                  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%2f5684%2fhistory-command-inside-bash-script%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    8 Answers
                    8






                    active

                    oldest

                    votes








                    8 Answers
                    8






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    29















                    Bash disables history in noninteractive shells by default, but you can turn it on.



                    #!/bin/bash
                    HISTFILE=~/.bash_history
                    set -o history
                    history | tail …


                    But if you're trying to monitor activity on that server, the shell history is useless (it's trivial to run commands that don't show up in the history). See How can I log all process launches in Linux.



                    If you're debugging a script then shell history is not the best way to get useful information. A much better tool is the debug trace facility: put set -x near the top of the script. The trace is written to standard error.






                    share|improve this answer




























                    • This refuses to work in a script: histtest.sh: 5: set: Illegal option -o history

                      – Ken Sharp
                      Jan 7 '16 at 2:56






                    • 4





                      @KenSharp That's because you tried to use it in an sh script (and your sh is dash juding by the exact wording of the error message). To access bash's history, you need to use bash (script starting with #!/bin/bash or #!/usr/bin/env bash).

                      – Gilles
                      Jan 7 '16 at 12:36






                    • 1





                      @KenSharp Yes it is. You obviously ran it under dash, given the error message. Bash does not have the error message Illegal option (it would say set: history: invalid option name).

                      – Gilles
                      Jan 7 '16 at 15:45











                    • the problem with this is that it adds all commands following set -o history to the history which is then going to be stuffed up with entries like if [... vars=$(... etc.

                      – nath
                      Dec 18 '17 at 2:42








                    • 1





                      @nath That's what the question asked for. It is pretty much pointless, as I point out. Monitoring activity is a hard problem that shell history won't solve. If you're debugging a script then set -x is a lot more useful.

                      – Gilles
                      Dec 18 '17 at 8:19


















                    29















                    Bash disables history in noninteractive shells by default, but you can turn it on.



                    #!/bin/bash
                    HISTFILE=~/.bash_history
                    set -o history
                    history | tail …


                    But if you're trying to monitor activity on that server, the shell history is useless (it's trivial to run commands that don't show up in the history). See How can I log all process launches in Linux.



                    If you're debugging a script then shell history is not the best way to get useful information. A much better tool is the debug trace facility: put set -x near the top of the script. The trace is written to standard error.






                    share|improve this answer




























                    • This refuses to work in a script: histtest.sh: 5: set: Illegal option -o history

                      – Ken Sharp
                      Jan 7 '16 at 2:56






                    • 4





                      @KenSharp That's because you tried to use it in an sh script (and your sh is dash juding by the exact wording of the error message). To access bash's history, you need to use bash (script starting with #!/bin/bash or #!/usr/bin/env bash).

                      – Gilles
                      Jan 7 '16 at 12:36






                    • 1





                      @KenSharp Yes it is. You obviously ran it under dash, given the error message. Bash does not have the error message Illegal option (it would say set: history: invalid option name).

                      – Gilles
                      Jan 7 '16 at 15:45











                    • the problem with this is that it adds all commands following set -o history to the history which is then going to be stuffed up with entries like if [... vars=$(... etc.

                      – nath
                      Dec 18 '17 at 2:42








                    • 1





                      @nath That's what the question asked for. It is pretty much pointless, as I point out. Monitoring activity is a hard problem that shell history won't solve. If you're debugging a script then set -x is a lot more useful.

                      – Gilles
                      Dec 18 '17 at 8:19
















                    29














                    29










                    29









                    Bash disables history in noninteractive shells by default, but you can turn it on.



                    #!/bin/bash
                    HISTFILE=~/.bash_history
                    set -o history
                    history | tail …


                    But if you're trying to monitor activity on that server, the shell history is useless (it's trivial to run commands that don't show up in the history). See How can I log all process launches in Linux.



                    If you're debugging a script then shell history is not the best way to get useful information. A much better tool is the debug trace facility: put set -x near the top of the script. The trace is written to standard error.






                    share|improve this answer















                    Bash disables history in noninteractive shells by default, but you can turn it on.



                    #!/bin/bash
                    HISTFILE=~/.bash_history
                    set -o history
                    history | tail …


                    But if you're trying to monitor activity on that server, the shell history is useless (it's trivial to run commands that don't show up in the history). See How can I log all process launches in Linux.



                    If you're debugging a script then shell history is not the best way to get useful information. A much better tool is the debug trace facility: put set -x near the top of the script. The trace is written to standard error.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 18 '17 at 8:22

























                    answered Jan 11 '11 at 21:07









                    GillesGilles

                    572k139 gold badges1182 silver badges1693 bronze badges




                    572k139 gold badges1182 silver badges1693 bronze badges
















                    • This refuses to work in a script: histtest.sh: 5: set: Illegal option -o history

                      – Ken Sharp
                      Jan 7 '16 at 2:56






                    • 4





                      @KenSharp That's because you tried to use it in an sh script (and your sh is dash juding by the exact wording of the error message). To access bash's history, you need to use bash (script starting with #!/bin/bash or #!/usr/bin/env bash).

                      – Gilles
                      Jan 7 '16 at 12:36






                    • 1





                      @KenSharp Yes it is. You obviously ran it under dash, given the error message. Bash does not have the error message Illegal option (it would say set: history: invalid option name).

                      – Gilles
                      Jan 7 '16 at 15:45











                    • the problem with this is that it adds all commands following set -o history to the history which is then going to be stuffed up with entries like if [... vars=$(... etc.

                      – nath
                      Dec 18 '17 at 2:42








                    • 1





                      @nath That's what the question asked for. It is pretty much pointless, as I point out. Monitoring activity is a hard problem that shell history won't solve. If you're debugging a script then set -x is a lot more useful.

                      – Gilles
                      Dec 18 '17 at 8:19





















                    • This refuses to work in a script: histtest.sh: 5: set: Illegal option -o history

                      – Ken Sharp
                      Jan 7 '16 at 2:56






                    • 4





                      @KenSharp That's because you tried to use it in an sh script (and your sh is dash juding by the exact wording of the error message). To access bash's history, you need to use bash (script starting with #!/bin/bash or #!/usr/bin/env bash).

                      – Gilles
                      Jan 7 '16 at 12:36






                    • 1





                      @KenSharp Yes it is. You obviously ran it under dash, given the error message. Bash does not have the error message Illegal option (it would say set: history: invalid option name).

                      – Gilles
                      Jan 7 '16 at 15:45











                    • the problem with this is that it adds all commands following set -o history to the history which is then going to be stuffed up with entries like if [... vars=$(... etc.

                      – nath
                      Dec 18 '17 at 2:42








                    • 1





                      @nath That's what the question asked for. It is pretty much pointless, as I point out. Monitoring activity is a hard problem that shell history won't solve. If you're debugging a script then set -x is a lot more useful.

                      – Gilles
                      Dec 18 '17 at 8:19



















                    This refuses to work in a script: histtest.sh: 5: set: Illegal option -o history

                    – Ken Sharp
                    Jan 7 '16 at 2:56





                    This refuses to work in a script: histtest.sh: 5: set: Illegal option -o history

                    – Ken Sharp
                    Jan 7 '16 at 2:56




                    4




                    4





                    @KenSharp That's because you tried to use it in an sh script (and your sh is dash juding by the exact wording of the error message). To access bash's history, you need to use bash (script starting with #!/bin/bash or #!/usr/bin/env bash).

                    – Gilles
                    Jan 7 '16 at 12:36





                    @KenSharp That's because you tried to use it in an sh script (and your sh is dash juding by the exact wording of the error message). To access bash's history, you need to use bash (script starting with #!/bin/bash or #!/usr/bin/env bash).

                    – Gilles
                    Jan 7 '16 at 12:36




                    1




                    1





                    @KenSharp Yes it is. You obviously ran it under dash, given the error message. Bash does not have the error message Illegal option (it would say set: history: invalid option name).

                    – Gilles
                    Jan 7 '16 at 15:45





                    @KenSharp Yes it is. You obviously ran it under dash, given the error message. Bash does not have the error message Illegal option (it would say set: history: invalid option name).

                    – Gilles
                    Jan 7 '16 at 15:45













                    the problem with this is that it adds all commands following set -o history to the history which is then going to be stuffed up with entries like if [... vars=$(... etc.

                    – nath
                    Dec 18 '17 at 2:42







                    the problem with this is that it adds all commands following set -o history to the history which is then going to be stuffed up with entries like if [... vars=$(... etc.

                    – nath
                    Dec 18 '17 at 2:42






                    1




                    1





                    @nath That's what the question asked for. It is pretty much pointless, as I point out. Monitoring activity is a hard problem that shell history won't solve. If you're debugging a script then set -x is a lot more useful.

                    – Gilles
                    Dec 18 '17 at 8:19







                    @nath That's what the question asked for. It is pretty much pointless, as I point out. Monitoring activity is a hard problem that shell history won't solve. If you're debugging a script then set -x is a lot more useful.

                    – Gilles
                    Dec 18 '17 at 8:19















                    6















                    I'm not sure if it actually uses the history capability when running non-interactively, otherwise every shell script you run would clutter up your command history.



                    Why not go directly to the source ${HOME}/.bash_history, replace history | tail -100 with tail -100 ${HOME}/.bash_history. (If you use timestamps you'd probably have to do something along the lines of grep -v ^# ${HOME}/.bash_history | tail -100).






                    share|improve this answer




























                    • Indeed, with timestamps, you should actually greq -v '^#[0-9]+$' (I sometimes "execute" comments in my shell...)

                      – PlasmaBinturong
                      Jan 18 '18 at 12:17











                    • And actually, in my case, I need to use the correct history line number, but there's a difference between the output of history and the output of the grep method...

                      – PlasmaBinturong
                      Jan 18 '18 at 12:21











                    • Ok, the fix was to synchronize the history list with the history file like this: history -a; history -c; history -r. (add, clear, read)

                      – PlasmaBinturong
                      Jan 18 '18 at 12:33


















                    6















                    I'm not sure if it actually uses the history capability when running non-interactively, otherwise every shell script you run would clutter up your command history.



                    Why not go directly to the source ${HOME}/.bash_history, replace history | tail -100 with tail -100 ${HOME}/.bash_history. (If you use timestamps you'd probably have to do something along the lines of grep -v ^# ${HOME}/.bash_history | tail -100).






                    share|improve this answer




























                    • Indeed, with timestamps, you should actually greq -v '^#[0-9]+$' (I sometimes "execute" comments in my shell...)

                      – PlasmaBinturong
                      Jan 18 '18 at 12:17











                    • And actually, in my case, I need to use the correct history line number, but there's a difference between the output of history and the output of the grep method...

                      – PlasmaBinturong
                      Jan 18 '18 at 12:21











                    • Ok, the fix was to synchronize the history list with the history file like this: history -a; history -c; history -r. (add, clear, read)

                      – PlasmaBinturong
                      Jan 18 '18 at 12:33
















                    6














                    6










                    6









                    I'm not sure if it actually uses the history capability when running non-interactively, otherwise every shell script you run would clutter up your command history.



                    Why not go directly to the source ${HOME}/.bash_history, replace history | tail -100 with tail -100 ${HOME}/.bash_history. (If you use timestamps you'd probably have to do something along the lines of grep -v ^# ${HOME}/.bash_history | tail -100).






                    share|improve this answer















                    I'm not sure if it actually uses the history capability when running non-interactively, otherwise every shell script you run would clutter up your command history.



                    Why not go directly to the source ${HOME}/.bash_history, replace history | tail -100 with tail -100 ${HOME}/.bash_history. (If you use timestamps you'd probably have to do something along the lines of grep -v ^# ${HOME}/.bash_history | tail -100).







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 11 '11 at 15:02

























                    answered Jan 11 '11 at 14:09









                    Kjetil JorgensenKjetil Jorgensen

                    1,1045 silver badges7 bronze badges




                    1,1045 silver badges7 bronze badges
















                    • Indeed, with timestamps, you should actually greq -v '^#[0-9]+$' (I sometimes "execute" comments in my shell...)

                      – PlasmaBinturong
                      Jan 18 '18 at 12:17











                    • And actually, in my case, I need to use the correct history line number, but there's a difference between the output of history and the output of the grep method...

                      – PlasmaBinturong
                      Jan 18 '18 at 12:21











                    • Ok, the fix was to synchronize the history list with the history file like this: history -a; history -c; history -r. (add, clear, read)

                      – PlasmaBinturong
                      Jan 18 '18 at 12:33





















                    • Indeed, with timestamps, you should actually greq -v '^#[0-9]+$' (I sometimes "execute" comments in my shell...)

                      – PlasmaBinturong
                      Jan 18 '18 at 12:17











                    • And actually, in my case, I need to use the correct history line number, but there's a difference between the output of history and the output of the grep method...

                      – PlasmaBinturong
                      Jan 18 '18 at 12:21











                    • Ok, the fix was to synchronize the history list with the history file like this: history -a; history -c; history -r. (add, clear, read)

                      – PlasmaBinturong
                      Jan 18 '18 at 12:33



















                    Indeed, with timestamps, you should actually greq -v '^#[0-9]+$' (I sometimes "execute" comments in my shell...)

                    – PlasmaBinturong
                    Jan 18 '18 at 12:17





                    Indeed, with timestamps, you should actually greq -v '^#[0-9]+$' (I sometimes "execute" comments in my shell...)

                    – PlasmaBinturong
                    Jan 18 '18 at 12:17













                    And actually, in my case, I need to use the correct history line number, but there's a difference between the output of history and the output of the grep method...

                    – PlasmaBinturong
                    Jan 18 '18 at 12:21





                    And actually, in my case, I need to use the correct history line number, but there's a difference between the output of history and the output of the grep method...

                    – PlasmaBinturong
                    Jan 18 '18 at 12:21













                    Ok, the fix was to synchronize the history list with the history file like this: history -a; history -c; history -r. (add, clear, read)

                    – PlasmaBinturong
                    Jan 18 '18 at 12:33







                    Ok, the fix was to synchronize the history list with the history file like this: history -a; history -c; history -r. (add, clear, read)

                    – PlasmaBinturong
                    Jan 18 '18 at 12:33













                    2















                    If you want to use the output of the history command from an active shell session in a script, you can use an alias to run the command first. Then, in the same alias, you can call the remainder of the script. With such a configuration, you can achieve essentially the same result as having the history command in the actual script.



                    For instance, you can create an alias like this, assuming the script's name is script.sh:



                    alias hy_tmp='history | tail -100 > /tmp/history.log ; bash /patch/to/script.sh'


                    And change the script to this:



                    #!/bin/bash
                    cd /tmp
                    uuencode history.log history.txt | mail -s "History log of server" hello@hel.com


                    I found this question while writing a process to combine, sort and synchronize ~/bash_history files on two computers so it'll be easy to search commands I've used in the past.



                    It's much less of a hassle to update my cumulative history file without having to log into a new shell to have ~/bash_history updated. For monitoring a server this will obviously not work, as mentioned in the other answers.



                    My usage in particular is:



                    alias hbye='history | cut -c 8- > /home/chris/.bash_history_c; bash /hby.sh


                    The script hby.sh then pulls all unique entries from all ~/.bash_history* files.






                    share|improve this answer






























                      2















                      If you want to use the output of the history command from an active shell session in a script, you can use an alias to run the command first. Then, in the same alias, you can call the remainder of the script. With such a configuration, you can achieve essentially the same result as having the history command in the actual script.



                      For instance, you can create an alias like this, assuming the script's name is script.sh:



                      alias hy_tmp='history | tail -100 > /tmp/history.log ; bash /patch/to/script.sh'


                      And change the script to this:



                      #!/bin/bash
                      cd /tmp
                      uuencode history.log history.txt | mail -s "History log of server" hello@hel.com


                      I found this question while writing a process to combine, sort and synchronize ~/bash_history files on two computers so it'll be easy to search commands I've used in the past.



                      It's much less of a hassle to update my cumulative history file without having to log into a new shell to have ~/bash_history updated. For monitoring a server this will obviously not work, as mentioned in the other answers.



                      My usage in particular is:



                      alias hbye='history | cut -c 8- > /home/chris/.bash_history_c; bash /hby.sh


                      The script hby.sh then pulls all unique entries from all ~/.bash_history* files.






                      share|improve this answer




























                        2














                        2










                        2









                        If you want to use the output of the history command from an active shell session in a script, you can use an alias to run the command first. Then, in the same alias, you can call the remainder of the script. With such a configuration, you can achieve essentially the same result as having the history command in the actual script.



                        For instance, you can create an alias like this, assuming the script's name is script.sh:



                        alias hy_tmp='history | tail -100 > /tmp/history.log ; bash /patch/to/script.sh'


                        And change the script to this:



                        #!/bin/bash
                        cd /tmp
                        uuencode history.log history.txt | mail -s "History log of server" hello@hel.com


                        I found this question while writing a process to combine, sort and synchronize ~/bash_history files on two computers so it'll be easy to search commands I've used in the past.



                        It's much less of a hassle to update my cumulative history file without having to log into a new shell to have ~/bash_history updated. For monitoring a server this will obviously not work, as mentioned in the other answers.



                        My usage in particular is:



                        alias hbye='history | cut -c 8- > /home/chris/.bash_history_c; bash /hby.sh


                        The script hby.sh then pulls all unique entries from all ~/.bash_history* files.






                        share|improve this answer













                        If you want to use the output of the history command from an active shell session in a script, you can use an alias to run the command first. Then, in the same alias, you can call the remainder of the script. With such a configuration, you can achieve essentially the same result as having the history command in the actual script.



                        For instance, you can create an alias like this, assuming the script's name is script.sh:



                        alias hy_tmp='history | tail -100 > /tmp/history.log ; bash /patch/to/script.sh'


                        And change the script to this:



                        #!/bin/bash
                        cd /tmp
                        uuencode history.log history.txt | mail -s "History log of server" hello@hel.com


                        I found this question while writing a process to combine, sort and synchronize ~/bash_history files on two computers so it'll be easy to search commands I've used in the past.



                        It's much less of a hassle to update my cumulative history file without having to log into a new shell to have ~/bash_history updated. For monitoring a server this will obviously not work, as mentioned in the other answers.



                        My usage in particular is:



                        alias hbye='history | cut -c 8- > /home/chris/.bash_history_c; bash /hby.sh


                        The script hby.sh then pulls all unique entries from all ~/.bash_history* files.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jul 19 '16 at 4:24









                        clkclk

                        1,6731 gold badge10 silver badges23 bronze badges




                        1,6731 gold badge10 silver badges23 bronze badges


























                            1















                            The history builtin seems to be disabled inside a shell script. See here: http://www.tldp.org/LDP/abs/html/histcommands.html



                            I have not found any official documentation about this.






                            share|improve this answer






























                              1















                              The history builtin seems to be disabled inside a shell script. See here: http://www.tldp.org/LDP/abs/html/histcommands.html



                              I have not found any official documentation about this.






                              share|improve this answer




























                                1














                                1










                                1









                                The history builtin seems to be disabled inside a shell script. See here: http://www.tldp.org/LDP/abs/html/histcommands.html



                                I have not found any official documentation about this.






                                share|improve this answer













                                The history builtin seems to be disabled inside a shell script. See here: http://www.tldp.org/LDP/abs/html/histcommands.html



                                I have not found any official documentation about this.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jan 11 '11 at 17:14









                                lesmanalesmana

                                15.4k11 gold badges62 silver badges73 bronze badges




                                15.4k11 gold badges62 silver badges73 bronze badges


























                                    1















                                    Create a script named script.sh as below. It creates a script named X and puts Y Number of lines of your history into it.



                                    #!/bin/bash
                                    SCRIPT_NAME=$1
                                    NUMBER_OF_LINES_BACK=$2

                                    # Enable History in a non interactive shell
                                    HISTFILE=~/.bash_history
                                    set -o history

                                    # echo shabang line and x number of lines of history to new script
                                    echo #!/bin/bash > $SCRIPT_NAME.sh; history | tail -n $NUMBER_OF_LINES_BACK >> $SCRIPT_NAME.sh;
                                    chmod u+x $SCRIPT_NAME.sh;

                                    # Open the newly created script with vim
                                    vim $SCRIPT_NAME.sh;
                                    ~


                                    Then if you want to create a script to a accomplish a task named "task" that you have been working on for the last 14 lines run



                                    script.sh task 14


                                    Then clean up your history to make a nice script!






                                    share|improve this answer


























                                    • histtest.sh: 5: set: Illegal option -o history

                                      – Ken Sharp
                                      Jan 7 '16 at 3:03


















                                    1















                                    Create a script named script.sh as below. It creates a script named X and puts Y Number of lines of your history into it.



                                    #!/bin/bash
                                    SCRIPT_NAME=$1
                                    NUMBER_OF_LINES_BACK=$2

                                    # Enable History in a non interactive shell
                                    HISTFILE=~/.bash_history
                                    set -o history

                                    # echo shabang line and x number of lines of history to new script
                                    echo #!/bin/bash > $SCRIPT_NAME.sh; history | tail -n $NUMBER_OF_LINES_BACK >> $SCRIPT_NAME.sh;
                                    chmod u+x $SCRIPT_NAME.sh;

                                    # Open the newly created script with vim
                                    vim $SCRIPT_NAME.sh;
                                    ~


                                    Then if you want to create a script to a accomplish a task named "task" that you have been working on for the last 14 lines run



                                    script.sh task 14


                                    Then clean up your history to make a nice script!






                                    share|improve this answer


























                                    • histtest.sh: 5: set: Illegal option -o history

                                      – Ken Sharp
                                      Jan 7 '16 at 3:03
















                                    1














                                    1










                                    1









                                    Create a script named script.sh as below. It creates a script named X and puts Y Number of lines of your history into it.



                                    #!/bin/bash
                                    SCRIPT_NAME=$1
                                    NUMBER_OF_LINES_BACK=$2

                                    # Enable History in a non interactive shell
                                    HISTFILE=~/.bash_history
                                    set -o history

                                    # echo shabang line and x number of lines of history to new script
                                    echo #!/bin/bash > $SCRIPT_NAME.sh; history | tail -n $NUMBER_OF_LINES_BACK >> $SCRIPT_NAME.sh;
                                    chmod u+x $SCRIPT_NAME.sh;

                                    # Open the newly created script with vim
                                    vim $SCRIPT_NAME.sh;
                                    ~


                                    Then if you want to create a script to a accomplish a task named "task" that you have been working on for the last 14 lines run



                                    script.sh task 14


                                    Then clean up your history to make a nice script!






                                    share|improve this answer













                                    Create a script named script.sh as below. It creates a script named X and puts Y Number of lines of your history into it.



                                    #!/bin/bash
                                    SCRIPT_NAME=$1
                                    NUMBER_OF_LINES_BACK=$2

                                    # Enable History in a non interactive shell
                                    HISTFILE=~/.bash_history
                                    set -o history

                                    # echo shabang line and x number of lines of history to new script
                                    echo #!/bin/bash > $SCRIPT_NAME.sh; history | tail -n $NUMBER_OF_LINES_BACK >> $SCRIPT_NAME.sh;
                                    chmod u+x $SCRIPT_NAME.sh;

                                    # Open the newly created script with vim
                                    vim $SCRIPT_NAME.sh;
                                    ~


                                    Then if you want to create a script to a accomplish a task named "task" that you have been working on for the last 14 lines run



                                    script.sh task 14


                                    Then clean up your history to make a nice script!







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 23 '15 at 3:58









                                    EricEric

                                    1192 bronze badges




                                    1192 bronze badges
















                                    • histtest.sh: 5: set: Illegal option -o history

                                      – Ken Sharp
                                      Jan 7 '16 at 3:03





















                                    • histtest.sh: 5: set: Illegal option -o history

                                      – Ken Sharp
                                      Jan 7 '16 at 3:03



















                                    histtest.sh: 5: set: Illegal option -o history

                                    – Ken Sharp
                                    Jan 7 '16 at 3:03







                                    histtest.sh: 5: set: Illegal option -o history

                                    – Ken Sharp
                                    Jan 7 '16 at 3:03













                                    0















                                    Every user have it's own history file which is result of history command.Instead of using history command in your shell script you can use history file for user.
                                    There will be a .bash_history file in home directory of user, that will be the history file for the user.






                                    share|improve this answer






























                                      0















                                      Every user have it's own history file which is result of history command.Instead of using history command in your shell script you can use history file for user.
                                      There will be a .bash_history file in home directory of user, that will be the history file for the user.






                                      share|improve this answer




























                                        0














                                        0










                                        0









                                        Every user have it's own history file which is result of history command.Instead of using history command in your shell script you can use history file for user.
                                        There will be a .bash_history file in home directory of user, that will be the history file for the user.






                                        share|improve this answer













                                        Every user have it's own history file which is result of history command.Instead of using history command in your shell script you can use history file for user.
                                        There will be a .bash_history file in home directory of user, that will be the history file for the user.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Nov 23 '15 at 9:51









                                        amit singhamit singh

                                        3223 silver badges9 bronze badges




                                        3223 silver badges9 bronze badges


























                                            0















                                            history command is disabled by default on bash script that's why even history command won't work in .sh file. for its redirection, kindly redirect bash_history file inside the .sh file.


                                            or history mechanism can be enabled also by mentioning history file and change run-time parameters as mentioned below

                                            #!/bin/bash
                                            HISTFILE=~/.bash_history
                                            set -o history

                                            note: mentioned above two lines on the top of the script file. now history command will work in history.





                                            share|improve this answer






























                                              0















                                              history command is disabled by default on bash script that's why even history command won't work in .sh file. for its redirection, kindly redirect bash_history file inside the .sh file.


                                              or history mechanism can be enabled also by mentioning history file and change run-time parameters as mentioned below

                                              #!/bin/bash
                                              HISTFILE=~/.bash_history
                                              set -o history

                                              note: mentioned above two lines on the top of the script file. now history command will work in history.





                                              share|improve this answer




























                                                0














                                                0










                                                0









                                                history command is disabled by default on bash script that's why even history command won't work in .sh file. for its redirection, kindly redirect bash_history file inside the .sh file.


                                                or history mechanism can be enabled also by mentioning history file and change run-time parameters as mentioned below

                                                #!/bin/bash
                                                HISTFILE=~/.bash_history
                                                set -o history

                                                note: mentioned above two lines on the top of the script file. now history command will work in history.





                                                share|improve this answer













                                                history command is disabled by default on bash script that's why even history command won't work in .sh file. for its redirection, kindly redirect bash_history file inside the .sh file.


                                                or history mechanism can be enabled also by mentioning history file and change run-time parameters as mentioned below

                                                #!/bin/bash
                                                HISTFILE=~/.bash_history
                                                set -o history

                                                note: mentioned above two lines on the top of the script file. now history command will work in history.






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered 15 mins ago









                                                linux.cnflinux.cnf

                                                1




                                                1


























                                                    -1















                                                    Short answer:



                                                    use history -p to perform history expansion explicitly.



                                                    An example follows.



                                                    One use case happens a lot for me is:




                                                    • previous command get a list of file names, and print to stdout,

                                                    • I need to edit those file with vim.


                                                    Since my bash has been set -o histexpand, usually what I did is typing



                                                    vim $(!!)


                                                    to edit those files listed by previous command.



                                                    Sadly sometimes mistake happens, so I enable verify by shopt -s histverify.



                                                    Now I can verify the expansion, with cost of one extra Return key.



                                                    Today I want to wrap those details into a bash function since I use them a lot,



                                                    function vk() {
                                                    set -o history && set -o histexpand;
                                                    vim -i ~/.viminfok $($(history -p !!));
                                                    }


                                                    Here I use two nested command substitution, the inner one to expand !! to previous command, the outer one to execute it and get the output.



                                                    Now I can achieve the same effect, with only three key, and one of those is Return!






                                                    share|improve this answer






























                                                      -1















                                                      Short answer:



                                                      use history -p to perform history expansion explicitly.



                                                      An example follows.



                                                      One use case happens a lot for me is:




                                                      • previous command get a list of file names, and print to stdout,

                                                      • I need to edit those file with vim.


                                                      Since my bash has been set -o histexpand, usually what I did is typing



                                                      vim $(!!)


                                                      to edit those files listed by previous command.



                                                      Sadly sometimes mistake happens, so I enable verify by shopt -s histverify.



                                                      Now I can verify the expansion, with cost of one extra Return key.



                                                      Today I want to wrap those details into a bash function since I use them a lot,



                                                      function vk() {
                                                      set -o history && set -o histexpand;
                                                      vim -i ~/.viminfok $($(history -p !!));
                                                      }


                                                      Here I use two nested command substitution, the inner one to expand !! to previous command, the outer one to execute it and get the output.



                                                      Now I can achieve the same effect, with only three key, and one of those is Return!






                                                      share|improve this answer




























                                                        -1














                                                        -1










                                                        -1









                                                        Short answer:



                                                        use history -p to perform history expansion explicitly.



                                                        An example follows.



                                                        One use case happens a lot for me is:




                                                        • previous command get a list of file names, and print to stdout,

                                                        • I need to edit those file with vim.


                                                        Since my bash has been set -o histexpand, usually what I did is typing



                                                        vim $(!!)


                                                        to edit those files listed by previous command.



                                                        Sadly sometimes mistake happens, so I enable verify by shopt -s histverify.



                                                        Now I can verify the expansion, with cost of one extra Return key.



                                                        Today I want to wrap those details into a bash function since I use them a lot,



                                                        function vk() {
                                                        set -o history && set -o histexpand;
                                                        vim -i ~/.viminfok $($(history -p !!));
                                                        }


                                                        Here I use two nested command substitution, the inner one to expand !! to previous command, the outer one to execute it and get the output.



                                                        Now I can achieve the same effect, with only three key, and one of those is Return!






                                                        share|improve this answer













                                                        Short answer:



                                                        use history -p to perform history expansion explicitly.



                                                        An example follows.



                                                        One use case happens a lot for me is:




                                                        • previous command get a list of file names, and print to stdout,

                                                        • I need to edit those file with vim.


                                                        Since my bash has been set -o histexpand, usually what I did is typing



                                                        vim $(!!)


                                                        to edit those files listed by previous command.



                                                        Sadly sometimes mistake happens, so I enable verify by shopt -s histverify.



                                                        Now I can verify the expansion, with cost of one extra Return key.



                                                        Today I want to wrap those details into a bash function since I use them a lot,



                                                        function vk() {
                                                        set -o history && set -o histexpand;
                                                        vim -i ~/.viminfok $($(history -p !!));
                                                        }


                                                        Here I use two nested command substitution, the inner one to expand !! to previous command, the outer one to execute it and get the output.



                                                        Now I can achieve the same effect, with only three key, and one of those is Return!







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Aug 31 '17 at 2:39









                                                        qeatzyqeatzy

                                                        1334 bronze badges




                                                        1334 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%2f5684%2fhistory-command-inside-bash-script%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

                                                            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                                                            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                                                            Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...