这基本上是 this question 的延续。以下脚本提示用户输入搜索字符串,然后返回包含该字符串的 history
命令的编号列表。
#!/bin/bash
read -p 'Search history for? ' string
i=0
OLDIFS=$IFS
IFS=$'\n'
HISTFILE="$HOME/.bash_history"
history -r
arr=( "$(history | grep -i "$string" | cut -c8-)" )
for item in ${arr[@]}
do
echo "$(( i++ )) $item"
done
我想通过要求用户选择列出的命令之一来扩展此功能
read -p 'select a command or type /q to quit ' n
if [[ $n = '/q' ]]; then
exit
else
for cmd in ${arr[$n]}
do
echo "$cmd"
done
fi
IFS=$OLDIFS
但是每次都不会返回任何内容。我以前曾成功地使用过这种相同的选择方法。为什么这在这个特定场景中不起作用?
最佳答案
也许您想使用内置选择:
#!/bin/bash
read -p 'Search history for? ' string
i=0
OLDIFS=$IFS
IFS=$'\n'
HISTFILE="$HOME/.bash_history"
history -r
arr=$(history | grep -i "$string" | cut -c8-)
select choice in $arr; do echo "your choice is $choice"; break; done
IFS=$OLDIFS
输出:
...
33) kill -l
#? 33
your choice is kill -l
关于arrays - echo 数组的元素不输出任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39941458/