一个shell的基础编程问题

如下的代码:

shellIFS=:
IFS=$'\n'
IFS=$'\n;='

给IFS赋值,为什么第2,3行要用到$号,为什么第一行不用,$号有什么作用吗?

阅读 3.1k
3 个回答
新手上路,请多包涵

Words of the form $aqstringaq are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:

\a
    alert (bell) 
\b
    backspace 
\e
    an escape character 
\f
    form feed 
\n
    new line 
\r
    carriage return 
\t
    horizontal tab 
\v
    vertical tab 
\\
    backslash 
\aq
    single quote 
\nnn
    the eight-bit character whose value is the octal value nnn (one to three digits) 
\xHH
    the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) 
\cx
    a control-x character
新手上路,请多包涵

shell小白一只,简单test了一下:

  #! /bin/bash
  IFS=:
  echo "$IFS"
  IFS='\n'
  echo "$IFS"
  IFS=$'\n'
  echo "$IFS"
  IFS=$'\n;='
  echo "$IFS"

Shell script的输出是:

:
\n


;=

具体$和不加$造成上述输出的原理我也不清楚,求其他大神解答~

加$符号将现执行'\n'转义,既将单引号''内的\n转为换行.而$则是获取这个转义后的结果,既为一个空行.
如果不使用$的话,eho "$IFS"将打印原始字符,因为"'\n'"中的'\n'被视作一个普通字符串.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题