echoで表示する内容にタブ

表題の通り。知らなかったのでメモ。

■ 環境

  • sh

■ echo -e

スクリプトの中で情報を表示する際に`echo`で出すが、見栄えをよくする為に文字列の途中でタブを入れたかったので下記のようにやってみたところイメージと違う。

$ echo "aaa\tbbb"
aaa\tbbb
$

シングルクォートで括っているわけでもないのにな、と思っていたら制御文字を有効にするにはオプションが必要なようであった。

$ man sh
  :
 echo [-neE] [arg ...]
  Output  the  args,  separated  by  spaces, followed by a newline.  The return status is always 0.  If -n is
  specified, the trailing newline is suppressed.  If the -e option is given, interpretation of the  following
  backslash-escaped characters is enabled.  The -E option disables the interpretation of these escape charac-
  ters, even on systems where they are interpreted by default.  The xpg_echo shell  option  may  be  used  to
  dynamically determine whether or not echo expands these escape characters by default.  echo does not inter-
  pret -- to mean the end of options.  echo interprets the following escape sequences:
  \a     alert (bell)
  \b     backspace
  \c     suppress trailing newline
  \e     an escape character
  \f     form feed
  \n     new line
  \r     carriage return
  \t     horizontal tab
  \v     vertical tab
  \\     backslash
  \0nnn  the eight-bit character whose value is the octal value nnn (zero to three octal digits)
  \xHH   the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)
  :
$

というわけで”-e“オプションをつけて再度実行する。

$ echo -e "aaa\tbbb"
aaa    bbb
$

思い通りの結果を得ることができた。

以上。

■ 関連

Macでの`echo -n`