1

I would like to be able to retrieve input from my shell history in order to set variables inside my script. I would then like to use these variables in an if loop, but I am unable to get the variable set correctly.

Input stage: My initial input would come through the command line. Below are some possibities.

-> string
-> string AA
-> string 99

This string is tied to an alias that launches my script. The main function of my script is below.

inputsubstring()
{
strings /user/.sh_history | grep '^\string' | tail -1 | cut -d' ' -f2
}

So initially, I would get a string that would look something like the following:

substring
substring AA
substring 99

Because I am using the cut command at the end of the function I would theoretically receive the following output.

AA
99

Now, setting the variable to the above command works find for the alphanumberic output, but doesn't work well for the string without the second field. In fact, I cannot get it to set. Running the script with the problematic string actually echos out information regarding the last alphanumeric value. How would I get this to work.

I've attempted to create another value like this:

secondvar=${first:-default}

But it has not worked.

Additionally: I attempted to use string length, and variable assignment, but that has not worked. What should I do?

UPDATE: Since I only need to get "string" by itself a certain amount of times, I made a separate function involving concatenating my history and looking at the last input.

laststring()
{
cat /user/history | tail -1
}
  • 1
    What does the .sh_history file contain? Do you need to run strings on it? You're also doing tail -1 on it, so there's not much to loop over, if looping over the output of that function is what you mean. Can you edit the question to contain some example of the input file contents? And please take a peek at the editing help, the part about code block formatting. – ilkkachu Dec 3 '17 at 18:08
  • grep '^\string' looks for lines which begin with one whitespace character followed by the letters t r i n g. This regexp will never match substring AA. I cannot fully understand what is it that you are asking, but you seem to want to find the second field separated by whitespace, or the null string is no such field exists; sed -e 's/$/ /' | cut -d' ' -f2 will do the trick. (The sed appends a space character, thus making sure that cut is satisfied.) – AlexP Dec 3 '17 at 23:31
0

You can use the history command to search for the command you want and assign a variable like this.

If you ran ls and history showed that this command is number 99 you would assign it to a variable like this:

var=!99

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.