Bash: Why use eval with variable expansion?
luyued 发布于 2011-03-10 03:02 浏览 N 次Bash: Why use eval with variable expansion?
Problem
I don't understand why I have to use eval
:
#!/bin/bash
cmd="date --date=\"1 days ago\""
$cmd # Doesn't work
eval $cmd # Works
Solution
Before the shell executes a command, it performs the following operations (check the manual for details):
- Syntax analysis (Parsing)
- Brace expansion
- Tilde expansion
- Parameter and variable expansion
- Command substitution
- Arithmetic expansion
- Word splitting
- Filename expansion
- Quote removal
It is important to realize that parsing takes place before parameter and command substitution. The result of a step n
is subject to the next steps (n+
), but the preceding steps (n-
) are not re-executed. In other words: after for example variable expansion (step 4) the result is not re-parsed (step 1).
In the example of the command:
$cmd # cmd="date --date=\"1 days ago\""
the command date --date=\"1 days ago\"
is the result of variable expansion (step 4). Quote removal (step 9) removes the backslashes and turns the command into date --date="1 days ago"
. But since parsing (step 1) already has taken place, "1 days ago" is not seen as 1 argument but as 3 separate arguments: "1
, days
and ago"
, which gives you the error message:
date: extra operand `ago"'
Try `date --help' for more information.
To force one more run through the parsing/expansion procedure, use:
eval $cmd
Now first $cmd
is expanded (steps 1-9) to date --date="1 days ago"
. Then eval
causes the expanded string to be re-parsed again (steps 1-9), resulting in the correct command:
date --date="1 days ago"
Wed Nov 29 08:11:46 CET 2006
类别:默认分类 查看评论
- 07-01· 北凉国的那些事(组诗)
- 07-01· 《乱世佛音》 第七章 巨变
- 07-01· 南匈奴始末(3)
- 06-30· 流浪在波希米尼亚
- 06-30· 希尼亚从大洋西岸放飞新
- 06-28· 瑪利亞之城 - 家庭日 "光
- 06-28· 至青年营弟兄姐妹的一封
- 06-26· 《三国群英大富翁》追忆
- 06-24· 东莞血汗工厂实录(281:沙田
- 06-22· 第一次看戏
- 06-22· 经典复刻,独一无二:试
- 06-22· 蓝旗营教学中心9月份盛大
- 06-22· 品牌折扣女装嫣然品牌折
- 06-21· IQVopdnkvdz 1100
- 06-21· kriyoylto8fyds'p;tyijyfuifiogoi
- 06-21· 巴黎春天缤纷圣诞 喜迎新
- 06-21· 晒JS宝宝贝贝些 咯
- 06-21· 司马氏的谥法和葬仪
- 06-21· [转载]司马氏的谥法和葬仪
- 06-21· 闲来蓟县看秋山