user556068 user556068 - 2 months ago 8
Bash Question

Bash one liner works but script does not

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?

Answer

The line echo "$(( i++))) $item" has one closing parentheses in excess.

echo "$(( i++ )) $item"

If you try to use history in a script, it will fail.
Try running this script:

#!/bin/bash
history

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:

#!/bin/bash
HISTFILE="$HOME/.bash_history"
history -r
history

That doesn't mean that commands will be written to the file, that's controlled by a different option.

#!/bin/bash

read -p 'Search history for? ' string

i=0
OLDIFS=$IFS
IFS=$'\n'

HISTFILE="$HOME/.bash_history"
history -r
arr=( "$(history | grep "$string" | cut -c8-)" )

for    item in ${arr[@]}
do     echo "$(( i++ )) $item"
done