2
1

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.

Shell Scriptでcatに文字列を渡す

Posted at

言語処理系のテストを書いていると、ファイルにプログラムを保存して処理系に渡すまでをシェルスクリプト内で完結させたい時があります。
catコマンドは、ターミナルでなら、入力し、Ctrl+Dで終了できますが、シェルスクリプトで同じことをしようとすると、そのままだと標準入力に書き込むことができません。
結論を言うと、<< 任意の文字列をコマンドの最後に書き込み、入力したい文字列を改行した後に書き、最後に任意の文字列で締めくくると、標準入力に文字列を書き込むことができます。

test.sh
# !/bin/bash
cat > testfile.txt << EOI
Hello, world
EOI

記号の<<は、囲まれた文字列を標準入力にリダイレクトする効果があります。
変種として、<<-があり、これはtab文字を無視する以外は、<<と同じです。

PythonのREPLなどの対話型プログラムでも有効です。

# !/bin/bash
python << EOI
print("hello")
print("goodbye")
n = 1 + 1
print(n)
EOI

参考サイト

2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?