[Shell Functions] [Shell Arrays] Unix Shell Basics ユニックス シェル 一歩前へ
目的
- 自分用備忘録
- 初心者支援
方針
- 思いつきで書き足して行く所存(長大にならないように)
対象
- Unix シェルプログラミング
を強いられてるの知識を一歩前進させたいと思ってるひと
システム
- CentOS7
- Bash
$ bash -version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
事前準備: 環境がないひとは作ろう
- VirtualBox + vagrant
vagrant box list | grep "centos/7"
vagrant box add centos/7
vagrant box update --box centos/7
mkdir -p ./vagrant/centos7/bash-study
cd ./vagrant/centos7/bash-study
vagrant init centos/7 -m
insert_line_to_Vagrantfile
config.vm.network "private_network", type: "dhcp"
sample
Vagrant.configure(2) do |config|
config.vm.box = "centos/7"
config.vm.network "private_network", type: "dhcp"
end
vagrant up
vagrant ssh
sudo yum -y update
- Google Compute Engine (GCP)
- Cloud Shell という機能を使うと WEB ブラウザ 経由でシェルが利用できて便利
[sample vm]
-
https://console.cloud.google.com/compute/instances
- Create an instance
- Zone: US-EAST*
- Machine Type: micro
- Boot disk: CentOS7
- Firewall: Allow HTTP, HTTPS (if needed)
参考価格 \$4.49/月, \$0.006/1時間 (2017/01/11 時点)
- Cloud Shell
- SSH ボタンを押すかプルダウンメニューから "Open in browser window" を選択
- あたらしいウィンドウが開いてログインした状態になってる。あら便利。
sudo yum -y update
本題1: Shell Functions
ref. https://www.gnu.org/software/bash/manual/html_node/Shell-Functions.html
ref. https://www.gnu.org/software/bash/manual/html_node/Compound-Commands.html
ref. https://www.gnu.org/software/bash/manual/html_node/Command-Grouping.html
TL;DR
- シェルスクリプトの中で何度か同じ処理を繰り返してるところはないですか?
- そんなときに Shell Functions を使ってスクリプトを簡素化しましょう
Syntax
name () compound-command [ redirections ]
or
function name [()] compound-command [ redirections ]
Grouping_Commands
{ list; }
Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.
Practice01
sample_01
cat << EOF > shell_func_01.sh
function echo_message
{
echo "\$message"
}
message="hello world"
echo_message
message="good day"
echo_message
EOF
cat shell_func_01.sh
output
function echo_message
{
echo "$message"
}
message="hello world"
echo_message
message="good day"
echo_message
execute
$ bash shell_func_01.sh
output
hello world
good day
本題2: Shell Arrays
ref. https://www.gnu.org/software/bash/manual/html_node/Arrays.html
TL;DR
- シェルスクリプトでも配列使えないかな?
- 使えます!
Syntax
name=(value1 value2 … )
Practice02
sample_02
cat << EOF > shell_func_02.sh
message_list=("hello world" "good day")
function echo_message
{
echo "\$message"
}
message=\${message_list[0]}
echo_message
message=\${message_list[1]}
echo_message
EOF
cat shell_func_02.sh
output
message_list=("hello world" "good day")
function echo_message
{
echo "$message"
}
message=${message_list[0]}
echo_message
message=${message_list[1]}
echo_message
execute
$ bash shell_func_02.sh
output
hello world
good day