ども、シローです。
今回はヒアドキュメント、ヒアストリングについて整理しました。
ヒアドキュメント、ヒアストリングとは
前回のリダイレクトの(https://shiro-secret-base.com/?p=1107)記事で<
記号は標準入力先をファイルに指定することができると紹介しました。
ただ、ファイルの中身ではなく、シェルスクリプト内に記述した内容を標準入力先にしたい場合はヒアドキュメント、ヒアストリングを使います。
ヒアドキュメント:複数行をコマンドの標準入力先に渡す
記述
1 2 3 |
コマンド << 終了文字列 ヒアドキュメントの内容 終了文字列 |
使用例:複数行を表示
here_document.sh
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/bin/bash cat << END NAME cat -- concatenate and print files SYNOPSIS cat [-benstuv] [file ...] DESCRIPTION The cat utility reads files sequentially, writing them to the standard output. The file operands are processed in command-line order. If file is a single dash ('-') or absent, cat reads from the standard input. If file is a UNIX domain socket, cat connects to it and then reads it until EOF. This complements the UNIX domain binding capability available in inetd(8). END |
1 2 3 4 5 6 7 8 9 |
$ bash here_document.sh NAME cat -- concatenate and print files SYNOPSIS cat [-benstuv] [file ...] DESCRIPTION The cat utility reads files sequentially, writing them to the standard output. The file operands are processed in command-line order. If file is a single dash ('-') or absent, cat reads from the standard input. If file is a UNIX domain socket, cat connects to it and then reads it until EOF. This complements the UNIX domain binding capability available in inetd(8). |
END
で括った箇所がcat
コマンドの入力値となって出力されている
使用例:htmlファイルを複製
コマンドを実行する引数に応じて、内容が変わるhtmlファイルをヒアドキュメントとリダイレクトを使って作成します。
create_html.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#!/bin/bash if [ -n ${1} ]; then fileName=${1} else fileName=sample fi if [ -n ${2} ]; then yourName=${2} else yourName=Shiro fi cat << END > ${1}.html <!doctype html> <html lang="ja"> <head> <meta charset="utf-8" /> </head> <body> <h1>Hello ${yourName}</h1> </body> </html> END |
1 2 3 4 5 6 7 8 9 10 11 |
$ bash here_document.sh sample1 Taro $ cat sample1.html <!doctype html> <html lang="ja"> <head> <meta charset="utf-8" /> </head> <body> <h1>Hello Taro</h1> </body> </html> |
ヒアストリング:1行をコマンドの標準入力に渡す
記述
1 |
コマンド <<< 文字列 |
使用例:変数を標準入力に渡す
here_string.sh
1 2 3 4 5 |
#!/bin/bash str=abc tr b B <<< "$str" |
1 2 |
$ bash here_string.sh aBc |
ちょっと他に利用方法が分からないので、これぐらいにしようと思います笑
まとめ
- 標準入力に複数行を渡したい場合はヒアドキュメント
<<
- 標準入力に1行を渡したい場合はヒアストリング
<<<
おしまい〜^^