如何执行存储在变量中的命令? [英] How to execute command stored in a variable?

查看:38
本文介绍了如何执行存储在变量中的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调用存储在变量中的某些命令的正确方法是什么?
1 和 2 之间有什么区别吗?

What is the correct way to call some command stored in variable?
Is there any differences between 1 and 2?

#!/bin/sh
cmd="ls -la $APPROOTDIR | grep exception"
#1
$cmd
#2
eval "$cmd"

推荐答案

Unix shell 在执行之前对每一行输入进行一系列转换.对于大多数 shell,它看起来像这样(取自 bash 手册页):

Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the bash manpage):

  • 初始分词
  • 大括号扩展
  • 波浪号扩展
  • 参数、变量和算术展开
  • 命令替换
  • 二次分词
  • 路径扩展(又名通配)
  • 去除引用

在参数扩展阶段使用$cmd直接将其替换为您的命令,然后进行所有以下转换.

Using $cmd directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.

使用 eval "$cmd" 直到引用删除阶段什么都不做,其中 $cmd 按原样返回,并作为参数传递给 eval,其作用是在执行前再次运行整个链.

Using eval "$cmd" does nothing until the quote removal phase, where $cmd is returned as is, and passed as a parameter to eval, whose function is to run the whole chain again before executing.

所以基本上,它们在大多数情况下是相同的,并且在您的命令使用转换步骤直到参数扩展时有所不同.例如,使用大括号扩展:

So basically, they're the same in most cases, and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:

$ cmd="echo foo{bar,baz}"
$ $cmd
foo{bar,baz}
$ eval "$cmd"
foobar foobaz

这篇关于如何执行存储在变量中的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆