我试图像这样在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命令之间的空白。