bash - 在命令替换中调用 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 命令之间的空格。
解决方案
推荐阅读
- python - 转换为字符串后如何从字典值中检索最后 5 个字符
- laravel - 事件侦听器未从 mount() 方法接收 Laravel Livewire 发射(但在从刀片发射时工作)
- python - 更改另一个文件python中变量的值
- javascript - 如何基于单选按钮隐藏和取消隐藏表单字段?
- laravel - 无法删除失败的作业(laravel 7)
- vb.net - 删除 WebBrowser 控件正在访问的文件 - VB.net
- javascript - 如何同时连接到多个 mikrotik?
- c# - .NET 5.0 打开选择文件夹对话框
- spring-boot - Spring Boot 中使用 RabbitListener 注解创建优先级队列
- scala - ScalaCheck 在有状态测试中收缩命令数据