5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

組み込みのechoと/bin/echoの違い

Last updated at Posted at 2017-01-11

c++のユニットテストでhttpのモックサーバーをsystem関数で作った時、Ubuntuでうまく動作しませんでした。

system( "echo -e 'HTTP/1.0 200 OK\\r\\nContent-Type: text/plain\\r\\n\\r\\nhoge' | nc -l 8080 > /dev/null &");

system関数は内部的に sh -c "command" の形式で実行されます。つまり、

$ /bin/sh -c "echo -e 'ho\nge'"

のような感じです。echo の -e オプションはエスケープシーケンスを解釈する指定です。
これをUbuntuで実行すると期待する結果になりません。

-e ho
ge

-eが余分です。
これは、Ubuntuでは/bin/shのデフォルトがdashで、dashの組み込みのechoに-eオプションが無いためです。

$ man dash

で確認してみるとたしかに -e オプションはありません。
元のテストコードは次のように /bin/echo にして対処しました。

system( "/bin/echo -e 'HTTP/1.0 200 OK\\r\\nContent-Type: text/plain\\r\\n\\r\\nhoge' | nc -l 8080 > /dev/null &");

まとめ

  • 組み込みコマンドと外部コマンドの仕様が異なる場合があるので注意する(echoに限らず)

また、外部コマンドの場合も環境によって仕様が異なる場合もあると思うため、注意が必要です。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?