Ubuntu: bash script to delete last 10 lines in histroy



Question:

i want to make a bash script to delete last 10 lines in the history that is what i made, but i still getting an error

#!/bin/bash  i= history | wc -1  j= $i-10  for x in {$i..$j}  do    history -d $x  done  

I can't figure out what is wrong, any idea ?


Solution:1

There are several errors.

i= history | wc -1

You've got spaces in here so you'd need to wrap this in "" to avoid an error, and additionally you've added an unneeded space after the equal sign. However, all you've done is create a variable containing "history | wc -1". Firstly, there is no "wc -1". I think you meant "wc -l", which counts the lines. Secondly, I think you wanted to actually run this command.

You could use:

  i=$(history | wc -l)  

However, it's always going to be 0 as the result, because you're in a subshell.

j= $i-10

You've added a space after the equal sign. You could use "j=$i-10", but that's not actually going to do any math.

Try something like:

  j=$(echo "${i}-10" | bc -l)  

You're probably going to want to write an if statement to handle senarios where i is 10 or less.

Try something like:

  if [[ "$i" -lt "11" ]]; then j="1"; fi  
for x in {$i..$j}

You can't use variables here. The result will be #..# instead of a list of numbers. You could get around this problem by creating a one-liner for do done statement that is echoed into a variable and then use eval to actually execute it. This way the $i and $j will already have been replaced with the actual numbers when the command is run.

Ultimately though, the entire approach is pointless, because when you run the history command in the shell script you're going to get zero as the result of the count, because you're in a subshell, and subshells do not report their history. To see what I mean, run several commands, and then run this script:

  #!/bin/bash  history | wc -l  

As you can see, the result is 0. Why? Because it's the history of the subshell, and the subshell doesn't report history. Even if you add other commands into the script before the history command, the result will be 0.

Start over. Look into editing the history file directly as @kos has suggested. Keep in mind commands from the current shell aren't written to the file until the shell exits.

Good luck.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »