Search code examples
bashscriptingshcommand-substitution

Unable to echo last executed within .sh script


Using following on

cmd=$(uname -a)

printf "["!:0"]"

gives me

[cmd1=Linux localhost.localdomain 2.6.32-300.10.1.el5uek #1 SMP Wed Feb 22 17:37:40 EST 2012 x86_64 x86_64 x86_64 GNU/Linux]

but when is done in test.sh

#!/bin/bash
output=$(uname -a)


printf "["!:0"]"

I'm getting

[!:0]

Thanks.


Solution

  • If you need to get the previous command executed inside a bash (v4+) script,

    #!/bin/bash -i
    # -i: interactive mode, enable history inside script
    set -o history  # enable history, for old bash versions
    
    cmd=$(uname -a)
    history | sed -n 'x;${s/ *[0-9]\+ *\(\S*\)/\1/p}'  # print the line before last history entry after removing index