读取终端中命令的变量

时间:2012-09-22 02:55:57

标签: linux bash shell terminal command

我这样做很好用

utnso@utnso-vm:~$ read command
ps -fea
utnso@utnso-vm:~$ $command
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 23:34 ?        00:00:02 /sbin/init
root         2     0  0 23:34 ?        00:00:00 [kthreadd]
root         3     2  0 23:34 ?        00:00:00 [ksoftirqd/0]
...

但是当试图运行此命令时,它失败了......

utnso@utnso-vm:~$ read command
ps -fea | grep bash
utnso@utnso-vm:~$ $command
ERROR: Garbage option.
********* simple selection *********  ********* selection by list *********
-A all processes                      -C by command name
-N negate selection                   -G by real group ID (supports names)
-a all w/ tty except session leaders  -U by real user ID (supports names)
-d all except session leaders         -g by session OR by effective group name
-e all processes                      -p by process ID
T  all processes on this terminal     -s processes in the sessions given


   ...
    ...
    ...
    ...
                        ********* misc options *********
-V,V  show version      L  list format codes  f  ASCII art forest
-m,m,-L,-T,H  threads   S  children in sum    -y change -l format
-M,Z  security data     c  true command name  -c scheduling class
-w,w  wide output       n  numeric WCHAN,UID  -H process hierarchy

有人知道发生什么事吗?

Thanx in advanced!

2 个答案:

答案 0 :(得分:5)

您不能将重定向放在变量中。让shell执行内容。

$ bash -c "$command"

答案 1 :(得分:4)

当您的命令行包含要扩展的单个参数时,例如

$ $command

bash执行以下操作:

  1. 展开参数,并对结果执行分词。
  2. 将第一个单词作为简单命令执行,将剩余的单词作为参数传递。
  3. 就是这样。不会进一步解析扩展以将结果作为任何类型的复合命令或变量赋值或重定向进行处理。

    如果你完全理解eval的工作原理并知道评估任意字符串的安全含义,那么需要将更复杂的内容传递给eval命令,而只传递 。在我看来,eval应被视为最后的工具,而不是方便。