[Linux] evalとは

文字列を評価、連結して実行する

hoge.txt

hoge hoge

fuga.txt

fuga fuga fuga

example.sh

#!/bin/bash
value='hoge'

#文字列としてコマンドを変数に格納
cmd='grep $value hoge.txt'
echo $cmd
eval $cmd

$ sh example.sh
grep $value hoge.txt
hoge hoge

#!/bin/bash

grep_text() {
	for txt_file in $(ls . | grep ".txt$"); do
		grep_result=$(grep $1 $txt_file)
		if [ $? -eq 0 ]; then
			eval echo $2
		fi
	done
}

query='hoge'
message='検索対象が見つかりました。見つかったファイル名:$txt_file'
grep_text $query "${message}"

query='fuga'
message='検索対象が見つかりました。見つかったファイル名:$grep_result'
grep_text $query "${message}"

$ sh success.sh
検索対象が見つかりました。見つかったファイル名:hoge.txt
検索対象が見つかりました。見つかったファイル名:fuga fuga fuga

何これ、やればやるほど次から次へと課題が出てくる

sedコマンド

文字列を全置換したり行単位で抽出したり、削除したり、テキスト処理できるコマンド
コマンドラインパラメータで指定して非対話的に一括処理もできる
sedはStream EDitorの略

### sedの構文
sed OPTIONS… [SCRIPT] [INPUTFILE…]
[SCRIPT]とは “s/foo/bar/g”
“-e”オプションで直後に[SCRIPT]が来る

$ echo “Tech Blog” | sed -e “s/Blog/Comment/g”
Tech Comment
$ echo “Tech Blog” | sed -e “s/ /-/g”
Tech-Blog

バックスラッシュはエスケープ
$ echo “Tech Blog” | sed -e “s/ /\!/”
Tech!Blog

二つ目に見つかった”o”を”_”に変換
$ echo “Hello World” | sed -e “s/o/__/2”
Hello W__rld

### ファイルの書き換え
$ echo “Hello World” > sample.txt
$ sed -e “s/World/Coffee/g” sample.txt
Hello Coffee
$ cat sample.txt
Hello World
$ sed -i -e “s/World/Shinbashi/g” sample.txt
$ cat sample.txt
Hello Shinbashi

他にも色々使い方ができる
取り敢えず置換ができると覚えておく

シェル・FTP接続でファイル転送する方法

putでファイルを転送し、getでファイルを取得する

### コマンドラインでSFTP接続する方法
$ sftp ubuntu@***.**.**.**
sftp> put sample.txt
Uploading sample.txt to /home/ubuntu/sample.txt
sample.txt 100%

### シェルでSFTPする方法
test.shにファイルの転送、取得を書いて、sample.shにftp接続する際のパスワードを書きます。
$ chmod +x test.sh
$ chmod +x sample.sh

test.sh

sftp ubuntu@***.**.***.** << END
get nodesource_setup.sh
put sample.txt
quit
END

sample.sh

#!/bin/bash
expect -c "
  set timeout 3
  spawn ./test.sh
  expect \"ubuntu@***.**.***.**'s password:\"
  send \"hogehoge\n\"
  interact
"

$ ./sample.sh
spawn ./test.sh
ubuntu@***.**.***.**’s password:
Connected to ***.**.***.**.
sftp> get nodesource_setup.sh
Fetching /home/ubuntu/nodesource_setup.sh to nodesource_setup.sh
/home/ubuntu/nodesource_setup.sh 100% 14KB 345.7KB/s 00:00
sftp> put sample.txt
Uploading sample.txt to /home/ubuntu/sample.txt
sample.txt 100% 4 0.3KB/s 00:00
sftp> quit

ほう、これがやりたかった。

sftp ubuntu@hoge.com としてもできるが、passwordの入力は同じか…

systemctl startを実行するshellを書いてcronで実行する

まず、hello deamonはdeactiveの状態
$ sudo systemctl status hello

### shellを書く
exe.sh

#!/bin/sh
 
LOG=`sudo systemctl start hello`

$ sudo chmod 0755 exe.sh

### shell実行
$ sh exe.sh

$ sudo systemctl status hello
● hello.service – hello daemon
Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
Active: active (running) since 水 2021-01-20 10:58:55 JST; 21s ago
Main PID: 7450 (hello.sh)
CGroup: /system.slice/hello.service
├─7450 /bin/bash /home/vagrant/dev/test3/hello.sh
└─7472 sleep 1

1月 20 10:58:55 localhost systemd[1]: Started hello daemon.
1月 20 10:58:55 localhost systemd[1]: Starting hello daemon…

### crontabでshellを実行
$ sudo vi /etc/crontab

* * * * * /bin/sh /home/vagrant/dev/test3/exe.sh

$ sudo systemctl status hello
● hello.service – hello daemon
Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
Active: active (running) since 水 2021-01-20 11:10:01 JST; 27s ago
Main PID: 7625 (hello.sh)
CGroup: /system.slice/hello.service
├─7625 /bin/bash /home/vagrant/dev/test3/hello.sh
└─7654 sleep 1

お、シェルで”sudo systemctl start”の実行までできました。
あとは、シェルをmysqldのプロセスが止まっていたらsudo systemctl restart mysqld.serviceにして、ec2にデプロイするだけですね。なるほど、シェルってなかなかとっつきにくいと思ってたけど、意外と便利やな。

systemctlとshellの理解を深める

### 最終ゴール
$ sudo systemctl restart mysqld.service
↑これをshellで実行したい

1.まずシェルを作ります。
hello.sh

#!/bin/bash
while true
do
	echo hello world >> /home/vagrant/dev/test3/hello.log
	sleep 1
done

2.実行権限
$ sudo chmod 0755 hello.sh

3./etc/systemd/systemの下にUnit定義ファイルを作成する
$ sudo vi /etc/systemd/system/hello.service

[Unit]
Description = hello daemon

[Service]
ExecStart = /home/vagrant/dev/test3/hello.sh
Restart = always
Type = simple

[Install]
WantedBy = multi-user.target

L ServiceのExecStartが実行したいコマンド
L Restart=alwaysはサーバが不意に落ちた時に対応

4. Unitがserviceとして認識されたか確認
$ sudo systemctl list-unit-files –type=service | grep hello
hello.service disabled

5. 起動してステータス確認
$ sudo systemctl enable hello
$ sudo systemctl start hello
$ sudo systemctl status hello
● hello.service – hello daemon
Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
Active: active (running) since 水 2021-01-20 10:35:02 JST; 14s ago
Main PID: 7220 (hello.sh)
CGroup: /system.slice/hello.service
├─7220 /bin/bash /home/vagrant/dev/test3/hello.sh
└─7235 sleep 1

1月 20 10:35:02 localhost systemd[1]: Started hello daemon.
1月 20 10:35:02 localhost systemd[1]: Starting hello daemon…

$ tail hello.log
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
$ sudo systemctl stop hello

$ sudo systemctl status hello
● hello.service – hello daemon
Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
Active: inactive (dead) since 水 2021-01-20 10:38:06 JST; 21s ago
Process: 7220 ExecStart=/home/vagrant/dev/test3/hello.sh (code=killed, signal=TERM)
Main PID: 7220 (code=killed, signal=TERM)

1月 20 10:35:02 localhost systemd[1]: Started hello daemon.
1月 20 10:35:02 localhost systemd[1]: Starting hello daemon…
1月 20 10:38:06 localhost systemd[1]: Stopping hello daemon…
1月 20 10:38:06 localhost systemd[1]: Stopped hello daemon.

systemctl コマンドは、”systemd” をコントロールするコマンド
なるほど、systemctl restart mysqld.serviceは、mysqldのdaemonを管理してるってことね。
やっと理解した。

shell

#!/bin/bash
n=0
for i in $(seq 1000)
do
	n=$(echo $n + $i | bc)
done
echo $n

vagrant@trusty:~/other$ sh main.sh
500500

#!/bin/bash
n=0
for i in $(seq 5)
do
	echo "${i}回目の実行です"
done

vagrant@trusty:~/other$ sh main.sh
1回目の実行です
2回目の実行です
3回目の実行です
4回目の実行です
5回目の実行です

#!/bin/bash
n=0
for i in $(seq 5)
do
	echo "$i * 3" | bc
done
#!/bin/bash
for i in $(seq 5)
do
	printf "$i + "
	[ $i -eq 5 ] && printf "0\n"
done | bc

echoは改行を付与するがprintfは改行を入れない
-eq はイコール

#!/bin/bash
cnt=0
if [ -z “$1”]; then
cat <&0 else cat "$1" fi | while read line do echo "Installing $line" go get -u "$line" & (( (cnt += 1) % 16 == 0 )) && wait done wait [/code] -z "$1" : $1が指定していないときはTrueを返す &0: 標準入力(ファイルディスクリプタ 0) >> 追記する

am拡張子はautomake template

#!/bin/bash
cat >>Makefile.am < [/code]

shellでメール送信

シェルでメールを送信したい
mail1.txt

From: hoge@gmail.com
To: hoge@gmail.com
Subject: Hello, e-mail!

Hi, can you see?

[vagrant@localhost python]$ cat mail1.txt |
> sendmail -i -t

i:入力されるメッセージ中の `.’ だけを含む行を無視
t:受け手をメッセージから読み取り

その2

#!/bin/bash

export PATH=$PATH:/usr/sbin

MAIL_TO="ore@gmail.com"
MAIL_FROM="noreply@hogehoge.com"
SUBJECT="テストメール"
DATA="データ"

mail_send () {

CAT << EOD | nkf -j -m0 | sendmail -t
FROM: ${MAIL_FROM}
To: ${MAIL_TO}
MIME-Version: 1.0
Content-Type: text/plain; charset="ISO-2022-JP"
Content-Transfer-Encoding: 7bit

メールが送信されます。
ここに${DATA}が入る

EOD
}

mail_send

exit 0

.bashrc, .bash_profile

When using bash, you can customize the usage environment to your linking.

bash_profile
It is executed once at login. For example, it will be loaded when you start the terminal app. You should set an environment variable(a variable declared by export) to what should be specifically set in this file.

.bashrc
It is executed once at shell startup. If you hit bash on the command line, .bashrc will be read again.(.bash_profile is not read). If you want to set it each time you start the shell, put the settings in this file.

You may want to set aliases, shell functions, and command line completion for what to set specifically in this file.

~/.bash_profile
~/.bashrc

shell, perlとphpの比較演算子

Perl
———————————
数値比較
> : より大きい
>= : より大きいか等しい
< : より小さい <= : より小さいか等しい == : 等しい != : 等しくない <=> : 比較

文字列比較
gt: より大きい
ge: より大きいか等しい
lt: より小さい
le: より小さいか等しい
eq: 等しい
ne: 等しくない
cmp: 比較

PHP
———————————
== : 等しい
=== : 同じ
!= : 等しくない
!=== : 同じでない
> : より大きい
< : より小さい >= : 以上
<= : 以下 <=> : より小さい等しいより多き

ん?なんだこの<=>って??あんまり見ないけど。

Shell
———————————
eq : equal to
ge : greater than or equal to
gt : greater than
le : less than or equal to
lt : less than
ne : not equal to

シェルは文字列か。なんか注意が必要ですな