Table of contents
Grammars
Function
13. Functions, Shell Scripting Tutorial
rename()
{
# expects to be called as: rename .txt .bak
FROM=$1
TO=$2
for i in *$FROM
do
j=`basename $i $FROM`
mv $i ${j}$TO
done
}
Test
8.Test, Shell Shellscript Tutorial
Loop
7.Loop, Shell Scripting Tutorial
SERVER_LIST=(server1 server2 server3 server4)
for server in "${SERVER_LIST[@]}"; do ssh $server grep "text" /log/tomcat/access.log; done;
Variable Expansion
toUpperCase: ${varName^^}
toLowerCase: ${varName,,}
length: ${#varName}
Tip
- How to manually expand a special variable (ex: ~ tilde) in bash
var="${var/#\~/$HOME}"
- Wait for key presss:
read -p "Press any key to continue... " -n1 -s
활용
File exists
- How to Check if a File or Directory Exists in Bash
-f
은 파일이 보통 파일임을 확인한다. 일단 존재여부만 확인하려면-e
옵션을 사용하는게 좋다FILE=/etc/resolv.conf if [ -e "$FILE" ]; then echo "$FILE exists." else echo "$FILE does not exist." fi
Args size check
- Check number of arguments passed to a Bash script
if [ "$#" -ne 1 ]; then echo "Illegal number of parameters" fi
Run log 만들기
#!/bin/bash
# redirect stdout/stderr to a file
dt=$(date '+%Y%m%d-%H');
_date=$(date '+%Y%m%d');
exec &> /log/log/${dt}.log
grep multiple servers
#!/bin/bash
CMD=$1
KEYWORD=$2
FILENAME=$3
SERVER_LIST=(service1 service2 service3 service4 service5 service6 service7 service8 service9)
for server in "${SERVER_LIST[@]}"; do
ssh $server "${CMD} ${KEYWORD} ${FILENAME}"
done