首页 > 解决方案 > 在命令替换中调用 grep 失败

问题描述

我正在尝试在 bash 中的命令替换中进行 grep 调用,如下所示:

status=$(dpkg -s elasticsearch | grep "Status")

但是当我在一个名为 的脚本中运行它时elk.sh,我得到以下输出:

./elk.sh: 47: ./elk.sh:  grep: not found

似乎当我使用命令替换时,找不到 grep。但是当我在我的脚本中正常调用它时,它照常工作。

你知道什么可能是错的吗?

编辑:由于我的代码不敏感,所以我在这里分享它,因为它可以帮助您了解问题所在。

请注意,file elk.sh返回:

elk.sh: POSIX shell script, UTF-8 Unicode text executable

这是代码:

#!/bin/sh

pInfo() {
    if [ "$#" -ne 1 ]; then
        echo "Invalid arguments: pInfo needs one string as argument."
        exit 1
    fi
    echo "\033[32m[INFO]\033[0m $1"
}

pError() {
    if [ "$#" -ne 1 ]; then
        echo "Invalid arguments: pError needs one string as arguments."
        exit 1
    fi
    echo "\033[31m[ERROR]\033[0m $1"
}

install_elk() {
    wget "https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.4.2.deb" -q --show-progress
    sudo dpkg -i "elasticsearch-6.4.2.deb"
    sudo apt-get install -f
    sudo rm -rRf "elasticsearch-6.4.2.deb"
}

which grep
echo $PATH
pInfo "Verifying ElasticSearch installation."
status=$(dpkg -s elasticsearch | grep Status)
if [ "$?" -ne 0 ] || [ -z "$status" ]; then
    pError "ElasticSearch is not installed."
    pInfo "Start the installation ? (y/n)"
    read answer
    if [ "$answer" != "y" ] && [ "$answer" != "n" ]; then
        pError "Invalid answer. Just type 'y' (yes) or 'n' (no)."
        exit 1
    fi
    if [ "$answer" = "y" ]; then
        pInfo "Installing ElasticSearch..."
        install_elk
    else
        pInfo "Not installing ElasticSearch."
        exit 2
    fi
fi

pInfo "ElasticSearch installed."

ps ax | grep -v grep | grep "elasticsearch" > /dev/null
if [ "$?" -eq 1 ]; then
    pInfo "ElasticSearch not running. Starting..."
    if [ ! -z "$(ps -p 1 | grep "systemd")" ]; then
        pInfo "System running systemd."
        sudo systemctl start elasticsearch.service
    else
        pInfo "System running init."
        sudo -i service elasticsearch start
    fi
fi

pInfo "ElasticSearch started."

exit 0

调用elk.sh提供以下输出:

$ ./elk.sh
/bin/grep
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
[INFO] Verifying ElasticSearch installation
[INFO] ElasticSearch installed
./elk.sh: 49: ./elk.sh:  grep: not found
[INFO] ElasticSearch not running. Starting...
[INFO] System running systemd.
[INFO] ElasticSearch started.

编辑:我发现了问题:像这样重写该行:

status=$(dpkg -s elasticsearch |grep "Status")

使命令正常工作。我只需要删除管道和 grep 命令之间的空格。

标签: bashshellgrep

解决方案


推荐阅读