linux - Ubuntu Shell 脚本问题 : convert output of command into variable

标签 linux bash shell

我尝试将一个命令行输出转换为(或存储为)变量。 命令是

ps -U root u | grep ruby | wc -l

输出是1,但是当我使用

$(ps -U root u | grep ruby | wc -l)

输出为

1: command not found

这里发生了什么? 这是我的快照 enter image description here

enter image description here

最佳答案

这里,

$(ps -U root u | grep ruby | wc -l)

您没有将输出保存到变量中。因此 shell 尝试执行结果(在您的情况下恰好是1)。由于它找不到名为 1 的命令/函数,因此您会收到错误。

您可能想要:

output=$(ps -U root u | grep ruby | wc -l)

现在,output 将具有 1,您可以使用它进行打印:

echo "${output}"

顺便说一句,grep 可以使用 -c 选项对自身进行计数。所以这里不需要 wc :

output=$(ps -U root u | grep -c ruby)
echo "${output}"

关于linux - Ubuntu Shell 脚本问题 : convert output of command into variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34292428/

相关文章:

python - NVIDIA Jetson Nano的PyTorch的Yocto Warrior Bitbake食谱

linux - rsync 仅同步当天文件

linux - 如何读取用户的多个输入以更改目录中正确存在的文件名?

linux - 如何编写shell脚本,自动进行文件转换?

c++ - OpenCV "Undefined reference to ' cv::imread' 等 C++

Java - RandomAccessFile(模拟 Linux tail 函数)

linux - 时间和时间?灵感来自触摸(1)

linux - 按回车键会导致 KDB 后台进程停止

linux - Bash 脚本日期 : Day before 15th and last day of month but it has to be a week day

linux - Shell命令将逗号分隔的字符串转换为双引号逗号分隔的字符串