将命令输出分配给 bash 中的变量

assign command output to variable in bash

我在尝试制作 bash 脚本时遇到问题。

这是命令:

ps -ef | grep "python ./" |awk '{print  }' | head -n 1

这是我保存变量的方式

first =$(ps -ef | grep "python ./" |awk '{print  }' | head -n 1)

当我执行这个脚本时,控制台显示:

./test.sh: line3: 2748: order not found

我做错了什么?谢谢

变量赋值是这样的:var=$(command)

所以在你的情况下,你写了一个 space 太多了。而不是:

first =$(ps -ef | grep "python ./" |awk '{print  }' | head -n 1)
     ^

你需要写:

first=$(ps -ef | grep "python ./" |awk '{print  }' | head -n 1)
     ^
     no spaces around = !!

您为什么会收到此错误消息?

./test.sh: line3: 2748: order not found

因为 first XX,Bash 知道您正在尝试 运行 使用参数 XX.

命令 first

附录:为了使命令更直接,没有那么多管道,使用单个 awk 作为 (谢谢!):

ps -ef | awk '/python \.\//{print ; exit}'
               ^^^^^^^^^^   ^^^^^^^^  ^^^^
                    |          |      stop processing, to get 1 value
                    |       print the 2nd block
               match lines with python ./