DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Shell中的替换和引用


Shell中的替换有4种形式,分别是:

Filename substitution (called globbing)

Value-based variable substitution

Command substitution

Arithmetic substitution

Filename substitution指文件名的通配符,包括*,?和[],分别表示任意长度字符串、单个字符和字符集合,例如:

ls ch*可以列出ch01 ch23等,ls ch?可以列出ch1 chs等,ls ch[01]可以列出ch0或者ch1

Value-based variable substitution是变量替换,基本方法是$variable_name。

下面的例子演示了两点:一是“:-”的用法(若HOST未赋值,则表达式值为localhost,HOST保持不变,详见[1] Hour 8: Substitution),二是字符串可以直接组合。

bash-3.00\( pp=\)"$ "

bash-3.00$ echo $pp

localhost$

bash-3.00\( pp=\)"$ "

bash-3.00$ echo $pp

/opt/godu$

Command substitution是将一个命令的输出进行替换,基本方法是用反引号或者$(...)括起命令,在指令替换有嵌套时用后者更方便,如

bash-3.00$ mydate=date

bash-3.00$ echo $mydate

Mon Sep 5 17:04:42 CST 2011 bash-3.00\( echo $(date) 2012年 05月 18日 星期五 14:34:19 CST Arithmetic substitution是进行算术表达式求值,基本格式是\)((...)),例如:

foo=$(( ((5 + 3*2) - 4) / 2 ))

单引号将内部的所有元字符(metacharactor)视为一般字符输出,双引号内$,`,\这些元字符(详见[1] Table 9.1)不被视为一般字符,例如:

bash-3.00$ echo 'I have $23' I have $23

bash-3.00\( echo "I have $23" I have 3 bash-3.00\) echo 'I have \\(23' I have \\)23

bash-3.00\( echo "I have \\)23" I have $23

bash-3.00\( echo 'date' date bash-3.00\) echo "date" 2012年 05月 18日 星期五 14:55:40 CST

bash-3.00\( echo "\)(date)" 2012年 05月 18日 星期五 14:57:07 CST

[1] Sriranga Veeraraghavan, Sams Teach Yourself Shell Programming in 24 Hours, Sams Publishing, 1999



Published

Sep 5, 2011

Last Updated

Sep 5, 2011

Category

Tech

Tags

  • shell 46
  • substitution 2
  • 引号 1

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor