打击一班班轮有效,但脚本不起作用 [英] Bash one liner works but script does not

查看:59
本文介绍了打击一班班轮有效,但脚本不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下脚本在运行时对我没有任何输出.我真的很困惑为什么这不起作用.

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?

推荐答案

echo"$((i ++)))$ item" 行中有一个多余的右括号.

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

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

如果您尝试在脚本中使用 history ,它将失败.
尝试运行此脚本:

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

#!/bin/bash
history

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

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

这篇关于打击一班班轮有效,但脚本不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆