Bash one liner可以使用,但是脚本没有

时间:2016-10-06 04:31:07

标签: arrays bash shell

以下脚本在运行时不会为我生成输出。我真的很困惑为什么这不起作用。

#!/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

然而,这个完全相同的事情(至少对我而言似乎是相同的)在一行中直接输入我的终端时工作正常:

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

我已将脚本设为可执行文件。我把它保存为多行和单行脚本。然而,没有任何保存的脚本产生任何输出。为什么在保存为脚本时不能正常工作,但可以直接在我的终端中正常工作?

2 个答案:

答案 0 :(得分:2)

echo "$(( i++))) $item"行有一个结束括号。

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

如果您尝试在脚本中使用history,则会失败 尝试运行此脚本:

#!/bin/bash
history

它将不会打印任何内容,因为没有存储历史记录(对于此shell的实例)。要读取历史记录,您需要为文件提供存储的历史记录,请调用内置history以阅读-r,最后您可以从内存中列出历史记录:

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

这并不意味着命令将被写入文件,而是由不同的选项控制。

#!/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

答案 1 :(得分:1)

看看this。显然,shell程序中禁用了bash history命令。但你可以根据这个链接解决它:

#!/bin/bash

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

set -o history
history
相关问题