【bash】シェルスクリプトで複数コマンドの実行結果を結合(OR/AND/XOR)する
2つのディレクトリをlsした結果を比較したりとか、awkで作った2種類のリストを比較したりとか、そういうことをしたかったので考えてみた。
解説
コマンドを && で繋いで () で括って sort して uniq してるだけ。
[def-concat_commands.sh]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
soniq(){ | |
sort | uniq $* | |
} | |
concat_commands() { | |
# $1 … method ( and | or | xor ) | |
# $2 … command | |
# $3 … command | |
local _arg="" | |
if [ "$1" = "and" ] ; then | |
_arg="-d" | |
fi | |
if [ "$1" = "xor" ] ; then | |
_arg="-u" | |
fi | |
((eval "$2" | soniq) && (eval "$3" | soniq)) | soniq ${_arg} | |
} |
[test_def-concat_commands.sh] ※テストコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
source `dirname $0`/def-concat_commands.sh | |
# Simplae Test | |
cat > test1.txt <<++EOD | |
test1 | |
test2 | |
test3 | |
test4 | |
++EOD | |
cat > test2.txt <<++EOD | |
test2 | |
test4 | |
test5 | |
test6 | |
++EOD | |
echo [--- TEST DATA ---] | |
echo [IN1] | |
cat test1.txt | |
echo | |
echo [IN2] | |
cat test2.txt | |
echo | |
# ①論理和 | |
echo [--- OR ---] | |
concat_commands or "cat test1.txt" "cat test2.txt" | |
echo count:`concat_commands or "cat test1.txt" "cat test2.txt" | wc -l` | |
echo | |
# ②論理積 | |
echo [--- AND ---] | |
concat_commands and "cat test1.txt" "cat test2.txt" | |
echo count:`concat_commands and "cat test1.txt" "cat test2.txt" | wc -l` | |
echo | |
# ③排他的論理和 | |
echo [--- XOR ---] | |
concat_commands xor "cat test1.txt" "cat test2.txt" | |
echo count:`concat_commands xor "cat test1.txt" "cat test2.txt" | wc -l` | |
echo | |
# ④左側ONLY | |
echo [--- IN1 ONLY ---] | |
concat_commands xor "cat test1.txt" 'concat_commands and "cat test1.txt" "cat test2.txt"' | |
echo count:`concat_commands xor "cat test1.txt" 'concat_commands and "cat test1.txt" "cat test2.txt"' | wc -l` | |
echo | |
rm test1.txt test2.txt |
注意点
- エラー処理とかはしていません。必要になったらするかも。
- 後半は全部テストコードです。
- ご利用の際は、
テストコード消したり適宜むにゃむにゃしたりしてねっ。