将输出导入cut命令

19
我试图获取执行脚本的shell名称。
为什么

echo $(ps | grep $PPID) | cut -d" " -f4

工作时执行

echo ps | grep $PPID | cut -d" " -f4

不会吗?

3个回答

25

这是因为

echo ps

该命令只会输出字符串ps,而不会运行程序ps。修正后的命令应为:

ps | grep $PPID | cut -d" " -f4

编辑补充:paxdiablo 指出ps | grep $PPID包含很多空格,这些空格会被echo $(ps | grep $PPID)压缩掉(因为$(...)的结果在没有双引号的情况下,会被按空格分成单独的参数,而echo输出所有参数时用空格分隔)。为解决这个问题,你可以使用tr来“挤压”重复的空格:

ps | grep $PPID | tr -s ' ' | cut -d' ' -f5

或者你可以坚持最初的选择。 :-)


由于某些原因,echo $(ps | grep $PPID) | cut -d" " -f4 会给我返回 "bash",而 ps | grep $PPID | cut -d" " -f4 只会返回一个空格。 - ZPS
不完全正确。第一个版本具有折叠空格的额外效果。 - paxdiablo
@paxdiablo:好观点!我会考虑编辑我的回答... - ruakh

7

第一行:

echo $(ps | grep $PPID) | cut -d" " -f4

says:

  • Execute ps | grep $PPID in a sub-shell
  • Return the output - which will be something like this:

    3559 pts/1 00:00:00 bash
    

    and then use that output as the first parameter of echo - which, in practice, means just echo the output

  • Then run cut -d" " -f4 on that - which gives you the command name in this case
第二个命令:
echo ps | grep $PPID | cut -d" " -f4

说:

  • 回显字符串ps
  • 使用$PPID在该字符串中进行grep - 这永远不会返回任何内容,因为$PPID包含数字,所以它永远不会是ps。 因此,grep什么也不返回
  • 使用上一个命令的输出作为输入来执行cut -d" " -f4 - 由于之前没有输出,因此您将得到空结果

2

我认为如果你仅运行echo ps,你就会看到为什么你的管道不起作用:

$ echo ps
ps

相反,请检查$0。请注意,它可能是-bashbash,这取决于它是否为登录shell。(好吧,任何shell——不仅仅是bash——但如果shell是登录shell,则会添加连字符。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接