0

I have a script which repeatedly waits for user entered text and then calls another script with the entered text. SO code credit, 'version 1'.

while IFS="" read -r -e -p 'Enter search term: ' -a search_term; do

    if [ "$search_term" != "" ]; then
        /path/to/script ${search_term[@]}

    else
        echo "Bye."
        exit 0
    fi

    history -s ${search_term[@]}

done

It calls the Bash builtin history command to allow scrolling up to previous entries.

The problem is when search_term begins with an option, e.g. -x exclude_this search term. This results in the following error: history: -x: invalid option. How do I force the history command to add the whole of search_term as a history entry and not to process any options that search_term may begin with? i.e. The whole of -x exclude_this search term should be added as a history entry.

Note: This can actually be solved by adding an initial empty string like this history -s "" ${search_term[@]} but each history entry is then prefixed by a space and repeated use adds a space each time pushing the entries further and further right. So this is a rather inelegant solution.

Thanks.

Community
  • 1
  • 1
mattst
  • 13,340
  • 4
  • 31
  • 43

1 Answers1

1

I found the answer myself in a question on SE Unix & Linux.

By using a double dash (--) in the history command you can stop a Bash built-in command from processing what follows as options. So all that I needed to change was this:

history -s -- ${search_term[@]}
Community
  • 1
  • 1
mattst
  • 13,340
  • 4
  • 31
  • 43