'Why won't a value in this bash script equal a command? [closed]

When I run this code, the variable "thing" doesn't change its value to the command. I've tried everything and I just can't get it to work. I want thing to equal something like "1 history cd /bin history cd /home/user/"

#!/bin/bash

val="thing"

function send () {
    thing
    thing=$(history | tail -n 2)
    echo $thing
    echo $val
    # echo $last
    if [ "$val" == *"this"* ]; then
        echo "yes"
    fi
    exit 1
}

send


Solution 1:[1]

If you wonder why $(history | tail -n 2) returns nothing, it is because history lists commands previously ran in the current shell.

But your script is a new shell instance, so it does not carry the history of commands you ran before you execute your script.

If you want that, you have to source the script, not execute it. To source, do:

$ . thescript.bash 

instead of

$ ./thescripts.bash

instead of this also

$ bash thescript.bash

Note: put your code in https://www.shellcheck.net/ to see syntax issues.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nic3500