Table of contents

  1. Grammars
    1. Function
    2. Test
    3. Loop
    4. Variable Expansion
  2. Tip
  3. 활용
    1. File exists
    2. Args size check
    3. Run log 만들기
    4. grep multiple servers

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

Shell Parameter Expansion:GNU

toUpperCase: ${varName^^}
toLowerCase: ${varName,,} length: ${#varName}

Tip

활용

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

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