'arguments'에 해당되는 글 1건

  1. 2020.04.20 [Bash] Bash function, array parameters, str replace 등

[Bash] Bash function, array parameters, str replace 등

ITWeb/개발일반 2020. 4. 20. 11:18

bash script 에서 function 사용은 호출 위치 보다 위에 function 선언이 되어 있어야 합니다.

#!/usr/bin/env bash

function 함수명() {
...
}

## 예제

#!/usr/bin/env bash

function helloWorld() {
  echo 'Hello World!!'
}

helloWorld

 

function  에 다중 array paramters 를 넘기는 예제는 아래와 같습니다.

#!/usr/bin/env bash

function deployElasticStack() {
  local instances=($1)
  local targets=($2)

  for instance in ${instances[@]}
  do

    local hostIpUser=($(echo $instance | tr ":" "\n"))

    for target in ${targets[@]}
    do
...중략...
    done
  done
}

selfHost=$(hostname -I|cut -f1 -d ' ')

instanceArr=("xxx.xxx.xxx.xxx:ubuntu" "xxx.xxx.xxx.xxx:ec2-user" "xxx.xxx.xxx.xxx:ubuntu")
metricbeatArr=("xxx.xxx.xxx.xxx" "xxx.xxx.xxx.xxx" "xxx.xxx.xxx.xxx")

deployElasticStack "${instanceArr[*]}" "${metricbeatArr[*]}" "$selfHost" "metricbeat"

 

해당 장비의 IP 정보를 가져 오는 예제는 아래와 같습니다.

$ hostname -I

$ hostname -I|cut -f1 -d ' '

$ ip route get 8.8.8.8 | sed -n '/src/{s/.*src *\([^ ]*\).*/\1/p;q}'

 

file 내 특정 문자열을 치환 하는 예제는 아래와 같습니다.

$ sed -i "s/소스문자열/치환문자열/g" configuration.yml

# osx 에서는 아래와 같이 합니다.
$ sed -i "" "s/소스문자열/치환문자열/g" configuration.yml

 

: