The following script produces no output for me when I run it. I am really confused as to why this isn't working.
#!/bin/bash
i=0
OLDIFS=$IFS
IFS=$'\n'
read -p 'Search history for? ' string
arr=( "$(history | grep "$string" | cut -c8-)" )
for item in ${arr[@]}
do
echo "$(( i++))) $item"
done
However this exact same thing (at least it seems the same to me) works fine when typed directly into my terminal in a single line:
i=0; OLDIFS=$IFS; IFS=$'\n'; read -p 'Search history for? ' string; arr=( "$(history | grep "$string" | cut -c8-)" ); for item in ${arr[@]}; do echo "$(( i++))) $item"; done
I've made the script executable. I've saved it as both a multi line and a single line script. Yet none of the saved scripts produce any output. Why doesn't this work when saved as a script but works fine typed directly into my terminal?
Have a look at this. Apparently the bash history command is disabled in shell programs. But you can get around it according to that link:
The line
echo "$(( i++))) $item"
has one closing parentheses in excess.If you try to use
history
in a script, it will fail.Try running this script:
It will print nothing because there is no history stored (for this instance of the shell). To read history you need to provide the file with the stored history, call the builtin
history
to read-r
and finally you can list the history from memory:That doesn't mean that commands will be written to the file, that's controlled by a different option.