Bash one liner works but script does not

2019-09-14 06:34发布

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?

2条回答
Root(大扎)
2楼-- · 2019-09-14 07:12

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:

#!/bin/bash

#Add this line in to set the history file to your.bash_history
HISTFILE=~/.bash_history 

set -o history
history
查看更多
SAY GOODBYE
3楼-- · 2019-09-14 07:16

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
IFS=$'\n' read -d '' -a arr <<<"$(history | grep "$string" | cut -c8-)"

for    item in ${arr[@]}
do     echo "$(( i++ )) $item"
done
查看更多
登录 后发表回答