디렉토리내의 json 파일 중 "system_user"와 find me라는 단어가 포함된 파일들을 찾아서 이동시키는 스크립트

#!/bin/bash

RESULT=(`find ./ -name "*.json" | xargs grep -l "\"system_user\"" | xargs grep -l "find me"`)
backup_dir="/var/log/backup"
for elem in "${RESULT[@]}"
do
	mv $elem "${backup_dir}"
done

 

 

'언어 > Sell Script' 카테고리의 다른 글

rsync, expect 를 활용한 data 백업  (0) 2022.12.09
Shell Script  (0) 2021.08.31
Shell ?  (0) 2021.08.26
#! /bin/bash

echo ===========================START============================
echo start time: `date`
USER="guest"
PW="pass" #보안확인 필요
IP="10.100.3.10"
echo "backup server IP: " $IP
conditionFile="/var/log/dataBackup_*.log"
ls $conditionFile
if [[ ! "$?" -eq 0 ]]; then
	echo "conditionFile not exists"
    echo end time: `date`
    exit 0
fi

echo "wating for 5 sec..."
sleep 5

expect << EOL

set time -1
spawn rsync -ahvz --include=*.log* --exclude=* /var/log/ ${USER}@${IP}:/var/log/
# /var/log/ 하위에 .log 포맷만 대상으로 처리
expect "password:"
send "${PW}\n"
expect "]#"

set time -1
spawn rsync -ahvz --exclude=exclusive_dir /var/log/file_data/ ${USER}@${IP}:/var/log/file_data/
# /var/log/file_data/ 하위에 exclusive_dir이라는 디렉토리는 제외하고 대상 처리
expect "password:"
send "${PW}\n"
expect "]#"

EOL

backup_dirs=(
"/var/log/backup" 
"/var/log/file_data_backup"
)

for elem in "${backup_dirs[@]}"
do
	if [ ! -d #elem ]; then
    	mkdir $elem
        echo mkdir $elem
    fi
done

mv /var/log/*.log "${backup_dirs[0]}"
sleep 1
mv /var/log/file_data/* "${backup_dirs[1]}"

echo end_time: `date`
echo ===========================END============================

백업 서버로 로그파일을 백업하는 스크립트 

Shell script?

  • 리눅스 command들을 단계적으로 수행하는것
  • 리눅스 command들을 모아 놓은 ASCII Text 파일
  • 특징
    • 실행 권한을 할당해야 실행가능
    • shell 구문은 기본 top-down 방식으로 해석해서 실행
    • # : 주석
    • #! /bin/bash : 셔뱅.해시뱅. 스크립트를 실행할 sub shell 이름
      • shell script를 만드는데 해당 sub shell로 실행
      • 해당 셔뱅을 넣지 않으면 login shell과 동일한 sub shell로 실행

sub shell? 

fastwon1@docker-ubuntu:~$ /bin/bash   // sub shell 실행
fastwon1@docker-ubuntu:~$ name=jaon   // 변수생성
fastwon1@docker-ubuntu:~$ echo $name  // 조회
jaon
fastwon1@docker-ubuntu:~$ exit // sub shell 종료
exit
fastwon1@docker-ubuntu:~$ echo $name // sub shell에서 생성한 변수 조회

fastwon1@docker-ubuntu:~$ exit
fastwon1@docker-ubuntu:~/ta$ export TEST=1    // parent shell에서 환경변수 설정
fastwon1@docker-ubuntu:~/ta$ env | grep TEST  // 환경변수 조회
TEST=1
fastwon1@docker-ubuntu:~/ta$ /bin/bash // sub shell 실행
fastwon1@docker-ubuntu:~/ta$ env | grep TEST // parent shell에서 설정한 환경변수 조회
TEST=1
fastwon1@docker-ubuntu:~$ export TEST4=1     // sub shell에서 환경변수 설정
fastwon1@docker-ubuntu:~$ env | grep TEST4   // sub shell에서 조회
TEST4=1
fastwon1@docker-ubuntu:~$ exit
exit
fastwon1@docker-ubuntu:~$ env | grep TEST4   // parent shell에서 환경변수 조회
fastwon1@docker-ubuntu:~$
fastwon1@docker-ubuntu:~$ cat > test.sh  //shift+insert ctrl+d
  • sub shell에서 생성한 변수는 sub shell 종료 후 조회할 수 없다.
  • parent shell에서 만든 환경변수는 sub shell에서 조회할 수 있다.
  • sub shell에서 만든 환경변수는 parent shell에서 조회할 수 없다.

 

Positional Parameters(위치 매개변수)

  • 입력하는 argument들을 $0, $1, $2와 같은 변수에 저장되어 스크립트로 전달
  • $0 : 스크립트 이름
  • $1 , $2 : 첫번째, 두번째 argument
  • $# : argument 수
  • $@ , $* : argument 파라미터 리스트
  • $$ : 로그인 shell의 process ID
  • $PWD : 현재 작업 디렉토리
  • $PPID : parent process ID
fastwon1@docker-ubuntu:~$ test.sh arg1 arg2 arg3 ....  \
>                          $0      $1   $2   $3 ..... $9 ${10}  //해당변수로 채워져서 스크립트로 전달
fastwon1@docker-ubuntu:~$ ps -f
UID          PID    PPID  C STIME TTY          TIME CMD
fastwon1    7953    7952  0  8월31 pts/0  00:00:00 -bash
fastwon1   14551    7953  0 03:10 pts/0    00:00:00 ps -f
fastwon1@docker-ubuntu:~$ echo $$
7953  //현재 shell의 process ID
fastwon1@docker-ubuntu:~$ echo $PWD  
/home/fastwon1
fastwon1@docker-ubuntu:~$ echo $PPID
7952  //현재 shell의 parent process ID
fastwon1@docker-ubuntu:~$
fastwon1@docker-ubuntu:~$
fastwon1@docker-ubuntu:~$


.....샘플테스트1
fastwon1@docker-ubuntu:~/test2$ cat parm_exam.sh -n
     1	#! /bin/bash
     2	
     3	echo "This script name : $0"
     4	echo "This first argument: $1"
     5	echo "This second argument: $2"
     6	echo "This third argument: $3"
     7	echo "This number of argument: $#"
     8	echo "This list of arguments: $@"
     9	echo "THis list of argument : $*"
    10	
fastwon1@docker-ubuntu:~/test2$ ./parm_exam.sh arg1 arg2 arg3
This script name : ./parm_exam.sh
This first argument: arg1
This second argument: arg2
This third argument: arg3
This number of argument: 3
This list of arguments: arg1 arg2 arg3
THis list of argument : arg1 arg2 arg3
fastwon1@docker-ubuntu:~/test2$


......샘플테스트2
fastwon1@docker-ubuntu:~/test2$ 
fastwon1@docker-ubuntu:~/test2$ cat ./parm_exam2.sh -n
     1	#! /bin/bash
     2	
     3	echo "[$1 directory]"
     4	echo $(date +%c)
     5	du -sh $1 2> /dev/null
     6	echo
fastwon1@docker-ubuntu:~/test2$ ./parm_exam2.sh /var/
[/var/ directory]
2021년 09월 01일 (수) 오전 03시 30분 02초
2.2G	/var/

fastwon1@docker-ubuntu:~/test2$


ls -la /usr/bin | grep "^-" | awk '{print $9}'




....echo 테스트
fastwon1@docker-ubuntu:~$ echo "hello"
hello
fastwon1@docker-ubuntu:~$ echo "hello\nworld"
hello\nworld
fastwon1@docker-ubuntu:~$ echo -e "hello\nworld"
hello
world
fastwon1@docker-ubuntu:~$ echo -e "hello\tworld"
hello	world
fastwon1@docker-ubuntu:~$ echo -e "hello\aworld"
helloworld
fastwon1@docker-ubuntu:~$ echo -e "hello\aworld"
helloworld
fastwon1@docker-ubuntu:~$ echo -n "hello"  //echo출력을 개행하지 않음.
hellofastwon1@docker-ubuntu:~$



....read 테스트
fastwon1@docker-ubuntu:~$ read tmp
1234
fastwon1@docker-ubuntu:~$ echo $tmp
1234
fastwon1@docker-ubuntu:~$ 
fastwon1@docker-ubuntu:~$ read name score
jaon 80
fastwon1@docker-ubuntu:~$ echo $name $score
jaon 80
fastwon1@docker-ubuntu:~$ read name score
jaon 80 classA
fastwon1@docker-ubuntu:~$ echo $score
80 classA
fastwon1@docker-ubuntu:~$ read -t10 -n8 passwd  //10초동안 8글자만 입력받음
fastwon1@docker-ubuntu:~$ read -t10 -n8 passwd  
12345678fastwon1@docker-ubuntu:~$ echo $passwd 
12345678
fastwon1@docker-ubuntu:~$ read -t10 -s passwd //10초동안 silent mode(입력받은 글자가 shell에 보이지 않음)로 입력받음
fastwon1@docker-ubuntu:~$ echo $passwd
123456789  
fastwon1@docker-ubuntu:~$ echo -n "name: "; read name
name: jaon
fastwon1@docker-ubuntu:~$ echo $name
jaon

 

printf

  • format
    • %d or %i : 숫자
    • %s : 문자
    • %f  : 실수
fastwon1@docker-ubuntu:~$ printf "hello linux shell\n"
hello linux shell
fastwon1@docker-ubuntu:~$ printf "Name: %s\tScore: %i\n" 
Name: 	Score: 0
fastwon1@docker-ubuntu:~$ printf "Name: %s\tScore: %i\n" JAON 80
Name: JAON	Score: 80
fastwon1@docker-ubuntu:~$ echo $NAME $Score

fastwon1@docker-ubuntu:~$ today=`date +%y-%m-%d-%H-%M-%S`
fastwon1@docker-ubuntu:~$ printf "Today is %s\n" $today
Today is 21-09-01-06-19-32
fastwon1@docker-ubuntu:~$ printf "|%10s|%10s|%10.2f|\n" ubuntu jaon 10  
|    ubuntu|      jaon|     10.00| //오른쪽 정렬되서 10글자까지 출력
fastwon1@docker-ubuntu:~$ 
fastwon1@docker-ubuntu:~$ printf "|%-10s|%-10s|%-10.2f|\n" ubuntu jaon 10
|ubuntu    |jaon      |10.00     |  //왼쪽 정렬되서 10글자까지 출력
fastwon1@docker-ubuntu:~$

 

 

exit

  • 0 : 프로그램 또는 명령이 성공으로 종료했음을 의미
  • 1 - 255
    • 1 : 일반 에러
    • 2: syntax error
    • 126 : 명령을 실행할 수 없음
    • 127 : 명령(파일) 이 존재하지 않음
    • 128 + N : 종료시그널 + N(kill -9 PID로 종료시 128 + 9 137)
  • $? : 종료 값 출력
fastwon1@docker-ubuntu:~$ kill -l
 1) SIGHUP	 2) SIGINT	 3) SIGQUIT	 4) SIGILL	 5) SIGTRAP
 6) SIGABRT	 7) SIGBUS	 8) SIGFPE	 9) SIGKILL	10) SIGUSR1
11) SIGSEGV	12) SIGUSR2	13) SIGPIPE	14) SIGALRM	15) SIGTERM
16) SIGSTKFLT	17) SIGCHLD	18) SIGCONT	19) SIGSTOP	20) SIGTSTP
21) SIGTTIN	22) SIGTTOU	23) SIGURG	24) SIGXCPU	25) SIGXFSZ
26) SIGVTALRM	27) SIGPROF	28) SIGWINCH	29) SIGIO	30) SIGPWR
31) SIGSYS	34) SIGRTMIN	35) SIGRTMIN+1	36) SIGRTMIN+2	37) SIGRTMIN+3
38) SIGRTMIN+4	39) SIGRTMIN+5	40) SIGRTMIN+6	41) SIGRTMIN+7	42) SIGRTMIN+8
43) SIGRTMIN+9	44) SIGRTMIN+10	45) SIGRTMIN+11	46) SIGRTMIN+12	47) SIGRTMIN+13
48) SIGRTMIN+14	49) SIGRTMIN+15	50) SIGRTMAX-14	51) SIGRTMAX-13	52) SIGRTMAX-12
53) SIGRTMAX-11	54) SIGRTMAX-10	55) SIGRTMAX-9	56) SIGRTMAX-8	57) SIGRTMAX-7
58) SIGRTMAX-6	59) SIGRTMAX-5	60) SIGRTMAX-4	61) SIGRTMAX-3	62) SIGRTMAX-2
63) SIGRTMAX-1	64) SIGRTMAX	
fastwon1@docker-ubuntu:~$ date
2021. 09. 02. (목) 03:30:15 KST
fastwon1@docker-ubuntu:~$ date > /dev/null
fastwon1@docker-ubuntu:~$ echo $?  //직전에 수행한 프로그램의 종료 코드값을 출력
0
fastwon1@docker-ubuntu:~$ date i
date: 잘못된 `i' 날짜
fastwon1@docker-ubuntu:~$ echo $?
1
fastwon1@docker-ubuntu:~$ 
fastwon1@docker-ubuntu:~$ data

명령어 'data' 을(를) 찾을 수 없습니다. 다음 명령어로 시도하시겠습니까:

  deb datliballegro4-dev의 명령어 ' (2:4.4.3.1-1)'
  deb datecoreutils의 명령어 ' (8.30-3ubuntu2)'

Try: sudo apt install <deb name>

fastwon1@docker-ubuntu:~$ echo $?
127  //명령이 존재하지 않음
fastwon1@docker-ubuntu:~$
fastwon1@docker-ubuntu:~$ sleep 1000
^C  //ctrl+c
fastwon1@docker-ubuntu:~$ echo $?
130  //SIGINT
fastwon1@docker-ubuntu:~$

 

비교 연산자

연산자 설명
x -eq y x값과 y값이 같으면 true 리턴
x -gt y x값이 y값보다 크면 true 리턴
x -ge y x값이 y값보다 크거나 같으면 true 리턴
x -lt y x값이 y값보다 작으면 true 리턴
x -le y x값이 y값보다 작거나 같으면 true 리턴
x -ne x값과 y값이 같지 않으면 true 리턴
-e file 파일이 존재하면 true 리턴
-d file 파일이 디렉토리이면 true 리턴
-f file 파일이면 true 리턴
-x file 파일이 실행가능하면 true 리턴
fastwon1@docker-ubuntu:~$ x=10
fastwon1@docker-ubuntu:~$ test $x -lt 5
fastwon1@docker-ubuntu:~$ echo $?
1
fastwon1@docker-ubuntu:~$ test $x -gt 5
fastwon1@docker-ubuntu:~$ echo $?
0
fastwon1@docker-ubuntu:~$ test -e /etc/passwd
fastwon1@docker-ubuntu:~$ echo $?
0
fastwon1@docker-ubuntu:~$ test -e /etc/passw
fastwon1@docker-ubuntu:~$ echo $?
1
fastwon1@docker-ubuntu:~$ test -d /tmp
fastwon1@docker-ubuntu:~$ echo $?
0
fastwon1@docker-ubuntu:~$ test -f /tmp
fastwon1@docker-ubuntu:~$ echo $?
1
fastwon1@docker-ubuntu:~$ 
fastwon1@docker-ubuntu:~$ [ $x -lt 5 ]
fastwon1@docker-ubuntu:~$ echo $?
1
fastwon1@docker-ubuntu:~$ [ $x -gt 5 ]
fastwon1@docker-ubuntu:~$ echo $?
0
fastwon1@docker-ubuntu:~$



fastwon1@docker-ubuntu:~$ a=`expr $a + \( 10 \* 10 \)`
fastwon1@docker-ubuntu:~$ echo $a
111
fastwon1@docker-ubuntu:~$

 

if ~ fi 

fastwon1@docker-ubuntu:~$ cat -n ./a.sh 
     1	#! /bin/bash
     2	
     3	echo -n "input number: "
     4	read x
     5	if [ $x -gt 5 ]
     6	then
     7		echo "$x is grater than 5"
     8	fi
     9	
    10	echo -n "input filePath: "
    11	read filePath
    12	
    13	if [ -e $filePath ]
    14	then
    15		ls -l /etc/passwd
    16	else
    17		echo "$filePath file does not exists"
    18	fi
    19	
fastwon1@docker-ubuntu:~$ ./a.sh 
input number: 10
10 is grater than 5
input filePath: /etc/passwd
-rw-r--r-- 1 root root 2849  8월 30 06:45 /etc/passwd
fastwon1@docker-ubuntu:~$

 

case in    )  )  ;; esc

.......테스트1
fastwon1@docker-ubuntu:~$ cat ./test.sh 
#! /bin/bash

echo -n "Do you want restart(yes/no)? "
read answer
case $answer in
	[yY]es) echo "System restart.";;
	[nN]o) echo "nothing to do.";;
	*) echo "entered incorrectly.";;
esac
fastwon1@docker-ubuntu:~$ ./test.sh 
Do you want restart(yes/no)? yes
System restart.
fastwon1@docker-ubuntu:~$ ./test.sh 
Do you want restart(yes/no)? Yes
System restart.
fastwon1@docker-ubuntu:~$ ./test.sh 
Do you want restart(yes/no)? no
nothing to do.
fastwon1@docker-ubuntu:~$ ./test.sh 
Do you want restart(yes/no)? No
nothing to do.
fastwon1@docker-ubuntu:~$ ./test.sh 
Do you want restart(yes/no)? y
entered incorrectly.
fastwon1@docker-ubuntu:~$


.......테스트2
fastwon1@docker-ubuntu:~$ cat -n ./case-exam.sh 
     1	#! /bin/bash
     2	
     3	cat << END
     4	-----------------------------
     5	1: Check disk usage
     6	2: Check the login user list
     7	------------------------------
     8	END
     9	echo -n "number:"
    10	read number
    11	case $number in
    12	1) df -h ;;
    13	2) who ;;
    14	*) echo "Bad choise!"
    15		exit 1 ;;
    16	esac
    17	exit 0
fastwon1@docker-ubuntu:~$ ./case-exam.sh 
-----------------------------
1: Check disk usage
2: Check the login user list
------------------------------
number:2
fastwon1 pts/0        2021-09-02 03:29 (10.100.0.2)
fastwon1@docker-ubuntu:~$ ./case-exam.sh 
-----------------------------
1: Check disk usage
2: Check the login user list
------------------------------
number:3
Bad choise!
fastwon1@docker-ubuntu:~$

 

 

expr

  • expr
    • 정수형 산술연산(+, -, *, /, % ), 논리연산(|, &), 관계연산(=, !=, >, >=, <, <=)
    • expr 사용시 제약사항
      1. 전체 문장은 ` 로 묶여야 한다.
      2.  * 와 ( ) 는 특수기호로 인식되므로 연산자로 인식하기 위해서는 \ 를 앞에 붙여야 한다. 또는 "" ''
      3. 연산에 들어간 모든 변수, 숫자, 기호 사이에는 공백이 있어야 한다.
      4. = 에는 공백이 없어야 한다.
fastwon1@docker-ubuntu:~$ 
fastwon1@docker-ubuntu:~$ type expr   // expr은 bash shell에 종속적이지 않다.
expr 는 /usr/bin/expr 임
..........expr 테스트
fastwon1@docker-ubuntu:~$ a=10
fastwon1@docker-ubuntu:~$ echo $a
10
fastwon1@docker-ubuntu:~$ a=`expr $a + 1`
fastwon1@docker-ubuntu:~$ echo $a
11
fastwon1@docker-ubuntu:~$ expr 5 + 5
10
fastwon1@docker-ubuntu:~$ x=10
fastwon1@docker-ubuntu:~$ expr $x - 10
0
fastwon1@docker-ubuntu:~$ expr $x '*' 2
20
fastwon1@docker-ubuntu:~$ expr $x '/' 2
5
fastwon1@docker-ubuntu:~$ expr $x '%' 2
0
fastwon1@docker-ubuntu:~$ x=10
fastwon1@docker-ubuntu:~$ x=$(expr $x + 1)
fastwon1@docker-ubuntu:~$ echo $x
11
fastwon1@docker-ubuntu:~$ x=$(expr $x + 1)
fastwon1@docker-ubuntu:~$ echo $x
12
fastwon1@docker-ubuntu:~$
fastwon1@docker-ubuntu:~$ x=10; y=20; z=$(expr $x '|' $y); echo $z
10
fastwon1@docker-ubuntu:~$ x=10; y=20; z=$(expr $x '&' $y); echo $z
10
fastwon1@docker-ubuntu:~$ x=10; y=20; z=$(expr $x '==' $y); echo $z
0
fastwon1@docker-ubuntu:~$ x=10; y=20; z=$(expr $x '!=' $y); echo $z
1
fastwon1@docker-ubuntu:~$ x=10; y=20; z=$(expr $x '<=' $y); echo $z
1
fastwon1@docker-ubuntu:~$ x=10; y=20; z=$(expr $x '>=' $y); echo $z
0
fastwon1@docker-ubuntu:~$

 

let

  • 정수형 산술연산, bit연산(<<, >>, &, |), 논리연산(&&, ||), 단항연산(++, +=, -=)
fastwon1@docker-ubuntu:~$ type let    // let은 bash shell에 종속된command이다.
let 는 쉘 내장임
fastwon1@docker-ubuntu:~$
........let 테스트
fastwon1@docker-ubuntu:~$ let sum=5+5
fastwon1@docker-ubuntu:~$ echo $sum
10
fastwon1@docker-ubuntu:~$ let sum=5*5
fastwon1@docker-ubuntu:~$ echo $sum
25
fastwon1@docker-ubuntu:~$  //let은 산술연산을 수행하는 command(+ - * /)

fastwon1@docker-ubuntu:~$ x=1
fastwon1@docker-ubuntu:~$ let x=x+1
fastwon1@docker-ubuntu:~$ echo $x
2
fastwon1@docker-ubuntu:~$ let x++
fastwon1@docker-ubuntu:~$ echo $x
3
fastwon1@docker-ubuntu:~$ let x+=1
fastwon1@docker-ubuntu:~$ echo $x
4
fastwon1@docker-ubuntu:~$ let x+=2
fastwon1@docker-ubuntu:~$ echo $x
6
fastwon1@docker-ubuntu:~$ x=1
fastwon1@docker-ubuntu:~$ ((x=x+1))
fastwon1@docker-ubuntu:~$ echo $x
2
fastwon1@docker-ubuntu:~$ ((x++))
fastwon1@docker-ubuntu:~$ echo $x
3
fastwon1@docker-ubuntu:~$

 

While

  • While 다음의 조건이 성공하는 동안 do~done 사이의 명령어 반복
fastwon1@docker-ubuntu:~$ cat -n ./while-exam.sh 
     1	#! /bin/bash
     2	
     3	num=10
     4	while [ $num -le 20 ]
     5	do 
     6		echo Number: $num
     7		((num++))
     8	done
     9	
fastwon1@docker-ubuntu:~$ ./while-exam.sh 
Number: 10
Number: 11
Number: 12
Number: 13
Number: 14
Number: 15
Number: 16
Number: 17
Number: 18
Number: 19
Number: 20
fastwon1@docker-ubuntu:~$

 

until

  • until 다음의 조건이 성공할때까지 동안 do~done 사이의 명령어 반복
fastwon1@docker-ubuntu:~$ cat -n ./until-exam.sh 
     1	#! /bin/bash
     2	
     3	x=10
     4	until [ $x -gt 20 ]
     5	do
     6		echo Number: $x
     7		((x++))
     8	done	
fastwon1@docker-ubuntu:~$ ./until-exam.sh 
Number: 10
Number: 11
Number: 12
Number: 13
Number: 14
Number: 15
Number: 16
Number: 17
Number: 18
Number: 19
Number: 20
fastwon1@docker-ubuntu:~$

 

 

Test

fastwon1@docker-ubuntu:~/test4$ cat -n ./add_user.sh 
     1	#! /bin/bash
     2	
     3	echo -n "New userName: "
     4	read userName
     5	while getent passwd $userName &> /dev/null #유저가 존재하지 않을때까지
     6	do
     7		echo "Sorry that account $userName is already taken, Please pick a different username."
     8		echo -n "New userName: "
     9		read userName
    10	done
    11	sudo useradd -m -s /bin/bash $userName
    12	echo $(id $userName)
fastwon1@docker-ubuntu:~/test4$

유저생성

 

fastwon1@docker-ubuntu:~/test4$ cat -n ./delete_user.sh 
     1	#! /bin/bash
     2	
     3	echo -n "Enter userName for delete: "
     4	read userName
     5	until getent passwd $userName &> /dev/null #유저가 존재할때까지
     6	do
     7		echo "Sorry that account $userName not exists"
     8		echo -n "Enter userName for delete: "
     9		read userName
    10	done
    11	sudo userdel -r $userName > /dev/null 2>&1
    12	result=$?
    13	if [ $result -eq 0 ] 
    14	then
    15		echo "Succeed to delete $userName"
    16	else
    17		echo "Failed to delete $userName"
    18	fi
fastwon1@docker-ubuntu:~/test4$

유저삭제

fastwon1@docker-ubuntu:~/test4$ cat -n ./whileif.sh 
     1	#! /bin/bash
     2	
     3	num=0
     4	while [ $num -lt 5 ]
     5	do
     6		echo "Number: $num"
     7		((num++))
     8		if [ "$num" == '2' ];then
     9		break 
    10		fi
    11	done
fastwon1@docker-ubuntu:~/test4$

 

 

for

  • 주어진 list만큼 do~done사이의 command를 반복실행
//////////////////////////////////////////////////////////////////////////
fastwon1@docker-ubuntu:~/test4$ cat -n ./for.sh 
     1	for NUM in $(seq 5)
     2	do 
     3		echo $NUM; done
     4	
fastwon1@docker-ubuntu:~/test4$
//////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////
fastwon1@docker-ubuntu:~/test4$ ls 
delete_user.sh  for.sh  for2.sh  result  test.sh  whileif.sh
fastwon1@docker-ubuntu:~/test4$ cat -n ./for2.sh 
     1	for file in *
     2	do
     3	ls $file
     4	done
fastwon1@docker-ubuntu:~/test4$ ./for2.sh 
delete_user.sh
for.sh
for2.sh
result
test.sh
whileif.sh
fastwon1@docker-ubuntu:~/test4$
//////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////
     1	#! /bin/bash
     2	arr=(9 8 7)
     3	arr2=("test1" "test2" "test3")
     4	for item in ${arr[@]};
     5	do
     6		echo $item
     7	done
     8	for item in ${arr2[@]};
     9	do
    10		echo $item
    11	done
fastwon1@docker-ubuntu:~/test4$ 
//////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////
fastwon1@docker-ubuntu:~/test4$ cat -n ./directory.sh 
     1	#! /bin/bash
     2	
     3	if [ ! -d ~/bachup ] 
     4	then
     5		mkdir ~/backup > /dev/null 2>&1
     6	fi
     7	for FILE in *
     8	do
     9		cp $FILE ~/backup/$FILE.old
    10	done
fastwon1@docker-ubuntu:~/test4$ 
//////////////////////////////////////////////////////////////////////////

 

fastwon1@docker-ubuntu:~/test4$ cat -n ./directory.sh 
     1	#! /bin/bash
     2	
     3	echo -n "enter directory path: "
     4	read path
     5	diCnt=0
     6	fiCnt=0
     7	echo $path
     8	for file in $path/*
     9	do
    10		if [ -d $file ];then
    11			((diCnt++))
    12		else
    13			((fiCnt++))
    14		fi
    15	done
    16	echo "directory count:" $diCnt
    17	echo "file count:" $fiCnt
fastwon1@docker-ubuntu:~/test4$ ./directory.sh 
enter directory path: /var/log
/var/log
directory count: 11
file count: 48
fastwon1@docker-ubuntu:~/test4$ ls -l /var/log | grep ^d | wc -l  //directory갯수 출력
11
fastwon1@docker-ubuntu:~/test4$ ls -l /var/log | grep ^- | wc -l //파일수 출력
48
fastwon1@docker-ubuntu:~/test4$

 

Shell

  • 사용자 명령어 해석기
  • 사용자가 입력한 명령어를 해석하여 Linux kernel에 전달

 

Shell 종류

종류 의미
Bourne shell(sh) AT&T 벨 연구소에서 개발한 Original shell
C shell(csh, tcsh) C언어 문법을 적용하여 만든 shell
History, aliases, job control, vi command edting and completetion 기능을 포함
korn shell(ksh) 기존 bourne shell에 C shell의 기능을 포함
Bourne-again shell(bash) GNU project로 만들어졌으며 csh, ksh이 가진 기능 포함하고있으며 bourne shell과 호환성이 높인 shell
MAC OS 기본 shell

 

 

fastwon1@docker-ubuntu:~$ cat /etc/shells         //현재 시스템에서 사용가능한 shell목록 출력
# /etc/shells: valid login shells
/bin/sh
/bin/bash
/usr/bin/bash
/bin/rbash
/usr/bin/rbash
/bin/dash
/usr/bin/dash
fastwon1@docker-ubuntu:~$ echo $SHELL              //현재 user의 shell 조회
/bin/bash
fastwon1@docker-ubuntu:~$ sudo chsh fastwon1       //shell변경
[sudo] fastwon1의 암호: 
fastwon1의 로그인 쉘을 변경하고 있습니다
새로운 값을 넣거나, 기본값을 원하시면 엔터를 치세요
	로그인 쉘 [/bin/bash]: /bin/sh
fastwon1@docker-ubuntu:~$ sudo grep fastwon1 /etc/passwd
fastwon1:x:1000:1000:fastwon1,,,:/home/fastwon1:/bin/sh
fastwon1@docker-ubuntu:~$

기본 조회

 

 

Shell의 변수?

  • 데이터를 담는 그릇
  • 선언할 필요없이 사용가능
  • 변수명: 문자, 숫사, _로 구성, 시작은 반드시 문자나 _로 시작
fastwon1@docker-ubuntu:~$ 
fastwon1@docker-ubuntu:~$ name=jh                    //변수 선언
fastwon1@docker-ubuntu:~$ echo $name                 //변수 조회
jh
fastwon1@docker-ubuntu:~$ set | grep name            // 변수 조회(현재 시스템에 존재하는 변수조회)
name=jh
        __git_eread "$g/rebase-merge/head-name" b;
                __git_eread "$g/rebase-apply/head-name" b;
        __git_ps1_branch_name=$b;
        b="\${__git_ps1_branch_name}";
    local upstream=git legacy="" verbose="" name="";
            name)
                name=1
        if [[ -n "$count" && -n "$name" ]]; then
            __git_ps1_upstream_name=$(git rev-parse 				--abbrev-ref "$upstream" 2>/dev/null);
                p="$p \${__git_ps1_upstream_name}";
                p="$p ${__git_ps1_upstream_name}";
                unset __git_ps1_upstream_name;
            COMPREPLY=($( apt-cache pkgnames $cur 2> /dev/null ))
    param="$dashoptions            $( apt-cache pkgnames $cur 2> /dev/null )            $( command ps axo pid | sed 1d )            $( _apport_symptoms )            $( compgen -G "${cur}*" )";
    compopt -o filenames;
        compopt -o filenames;
        compopt -o filenames 2> /dev/null;
        compopt -o filenames;
        COMPREPLY+=($(compgen -A hostname -P "$prefix$user" -S "$suffix" -- "$cur"));
_pnames () 
        [[ $result -gt 0 ]] && compopt -o filenames 2> /dev/null;
        echo "bash_completion: $FUNCNAME: usage: $FUNCNAME" "[-v varname value] | [-aN varname [value ...]] ..." 1>&2;
    local userland=$(uname -s);
fastwon1@docker-ubuntu:~$ unset name                               //변수 제거
fastwon1@docker-ubuntu:~$ echo $name

fastwon1@docker-ubuntu:~$

변수 선언 조회 제거

 

 

Shell의 환경변수?

  • 동작 되는 프로그램에게 영향을 주는 변수
  • 실행되는 애플리케이션에서 전달

환경변수 선언

  • export valName=value
fastwon1@docker-ubuntu:~$ export NAME=jh                   //환경변수 설정
fastwon1@docker-ubuntu:~$ echo $NAME                       //환경변수 조회
jh
fastwon1@docker-ubuntu:~$ env | grep NAME                  //환경변수 조회
NAME=jh
LOGNAME=fastwon1
fastwon1@docker-ubuntu:~$ echo $HOME
/home/fastwon1
fastwon1@docker-ubuntu:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
fastwon1@docker-ubuntu:~$ echo $USER
fastwon1
fastwon1@docker-ubuntu:~$ echo $SHELL
/bin/bash
fastwon1@docker-ubuntu:~$

환경변수 설정 및 조회

 

 

Metacharacters

  • Shell에서 특별히 의미를 정해 놓은 문자들
Metacharacters 의미
&&  || AND, OR 문자
< > >> redirection 문자
* ? [ ] {} glob 문자

[] : 집합
"" '' \ Quoting 문자 : 메타문자의 의미를 제거하고 단순 문자로 변경

Double Quotes("") : "" 내의 모든 메타문자의 의미를 제거, 단 $, ``는 제외
Single Quotes('')'' 내의 모든 메타문자의 의미를 제거
Bachslash(\) : \ 바로 뒤에오는 메타 문자의 의미를 제거
() nesting command

$(command)
`command`

$ echo "Today is $(date)"
$ echo "Today is `date`"
alias shell 명령어에 새로운 이름을 부여
명령들을 조합하여 새로운 이름의 명령생성

alias 등록: alias name='command'
alias 확인: alias or alias name
alias 삭제: unalias name
root@docker-ubuntu:/home/fastwon1/tmp# echo *          //모든 파일이름 출력
abc test1 test2 test3 test4 test5 tt
root@docker-ubuntu:/home/fastwon1/tmp# echo a*         //a로 시작하는 파일이름 출력
abc
root@docker-ubuntu:/home/fastwon1/tmp# echo ab*        //ab로 시작하는 파일이름 출력
abc
root@docker-ubuntu:/home/fastwon1/tmp# echo ?          // 파일이름의 길이가 1인 파일 출력
?
root@docker-ubuntu:/home/fastwon1/tmp# echo ???        // 파일이름의 길이가 3인 파일 출력
abc
root@docker-ubuntu:/home/fastwon1/tmp# echo ????       // 파일이름의 길이가 4인 파일 출력
????
root@docker-ubuntu:/home/fastwon1/tmp# echo ?????      // 파일이름의 길이가 5인 파일 출력
test1 test2 test3 test4 test5
root@docker-ubuntu:/home/fastwon1/tmp# ls
abc  test1  test2  test3  test4  test5  tt
root@docker-ubuntu:/home/fastwon1/tmp# touch sequenceFileName{1..10} //파일이름에 1~10까지의 순서를 붙여서 파일생성 
root@docker-ubuntu:/home/fastwon1/tmp# ls
abc                sequenceFileName10  sequenceFileName3  sequenceFileName5  sequenceFileName7  sequenceFileName9  test2  test4  tt
sequenceFileName1  sequenceFileName2   sequenceFileName4  sequenceFileName6  sequenceFileName8  test1              test3  test5
root@docker-ubuntu:/home/fastwon1/tmp# ls
abc                sequenceFileName10  sequenceFileName3  sequenceFileName5  sequenceFileName7  sequenceFileName9  test2  test4  tt
sequenceFileName1  sequenceFileName2   sequenceFileName4  sequenceFileName6  sequenceFileName8  test1              test3  test5
root@docker-ubuntu:/home/fastwon1/tmp# ls [a-z]*   // a~z까지 문자 중 하나를 가지는 파일 출력
abc                sequenceFileName10  sequenceFileName3  sequenceFileName5  sequenceFileName7  sequenceFileName9  test2  test4  tt
sequenceFileName1  sequenceFileName2   sequenceFileName4  sequenceFileName6  sequenceFileName8  test1              test3  test5
root@docker-ubuntu:/home/fastwon1/tmp# ls [s-z]*  // s~z까지 문자 중 하나를 가지는 파일 출력
sequenceFileName1   sequenceFileName2  sequenceFileName4  sequenceFileName6  sequenceFileName8  test1  test3  test5
sequenceFileName10  sequenceFileName3  sequenceFileName5  sequenceFileName7  sequenceFileName9  test2  test4  tt
root@docker-ubuntu:/home/fastwon1/tmp# ls [t-z]* // t-z까지 문자중 하나를 가지는 파일 출력
test1  test2  test3  test4  test5  tt
root@docker-ubuntu:/home/fastwon1/tmp# ls
abc                sequenceFileName10  sequenceFileName3  sequenceFileName5  sequenceFileName7  sequenceFileName9  test2  test4  tt
sequenceFileName1  sequenceFileName2   sequenceFileName4  sequenceFileName6  sequenceFileName8  test1              test3  test5
root@docker-ubuntu:/home/fastwon1/tmp# ls [^s]*  // s로 시작하는 파일이름 제외하여 출력
abc  test1  test2  test3  test4  test5  tt
root@docker-ubuntu:/home/fastwon1/tmp# ls [^s-t]* // s~t까지로 시작하는 파일이름 제외하여 출력
abc
root@docker-ubuntu:/home/fastwon1/tmp# ls [s^]* // s로 시작하는 파일만 출력
sequenceFileName1   sequenceFileName2  sequenceFileName4  sequenceFileName6  sequenceFileName8
sequenceFileName10  sequenceFileName3  sequenceFileName5  sequenceFileName7  sequenceFileName9
root@docker-ubuntu:/home/fastwon1/tmp# ls [^s^t]* //s , t로 시작하는 파일을 제외하여 출력
abc
root@docker-ubuntu:/home/fastwon1/tmp# ls [a^]* // a로 시작하는 파일만 출력
abc
root@docker-ubuntu:/home/fastwon1/tmp# date     // 현재시간 출력
2021. 08. 27. (금) 04:09:00 KST
root@docker-ubuntu:/home/fastwon1/tmp# 
root@docker-ubuntu:/home/fastwon1/tmp# echo 'Today is date' // 현재시간 출력 실패
Today is date
root@docker-ubuntu:/home/fastwon1/tmp# echo 'Today is $(date)' //현재시간 출력 실패
Today is $(date)
root@docker-ubuntu:/home/fastwon1/tmp# echo "Today is $(date)" //현재 시간 출력
Today is 2021. 08. 27. (금) 04:09:19 KST
root@docker-ubuntu:/home/fastwon1/tmp# echo "Today is `date`" // $(date)와 동일하게 출력
Today is 2021. 08. 27. (금) 04:10:57 KST
root@docker-ubuntu:/home/fastwon1/tmp# date +%Y-%d-%m-%H-%M-%S  //date를 formatting하여 출력
2021-27-08-04-16-25
root@docker-ubuntu:/home/fastwon1/tmp# touch report-$(date  +%Y-%d-%m-%H-%M-%S) //formatting한 문자로 파일생성
root@docker-ubuntu:/home/fastwon1/tmp# ls
report-2021-27-08-04-16-41
root@docker-ubuntu:/home/fastwon1/tmp# touch report-`date  +%Y-%d-%m-%H-%M-%S` //formatting한 문자로 파일생성
root@docker-ubuntu:/home/fastwon1/tmp# ls
report-2021-27-08-04-16-41  report-2021-27-08-04-16-54
root@docker-ubuntu:/home/fastwon1/tmp#

metacharacter 테스트

 

root@docker-ubuntu:/home/fastwon1/tmp# alias c=clear    //alias 설정
root@docker-ubuntu:/home/fastwon1/tmp# alias
alias c='clear'  //확인
alias comp='docker-compose'
alias cri='docker rmi -f `docker images -a -q`'
alias crm='docker rm -f `docker ps -a -q`'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias h='history'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
alias rm='rm -i'
root@docker-ubuntu:/home/fastwon1/tmp# unalias c        //alias 삭제
root@docker-ubuntu:/home/fastwon1/tmp# alias
alias comp='docker-compose'
alias cri='docker rmi -f `docker images -a -q`'
alias crm='docker rm -f `docker ps -a -q`'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias h='history'
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias ls='ls --color=auto'
alias rm='rm -i'
root@docker-ubuntu:/home/fastwon1/tmp#

alias 등록 삭제

 

Shell Prompt란?

  • PS1 변수를 이용해 shell의 기본 프롬프트 모양을 설정
특수문자 의미
\h 호스트이름
\u 사용자 이름
\w 절대경로 작업디렉토리
\W 상대경로 작업디렉토리
\d 오늘날짜
\t 현재시간
\$ $또는 # 프롬프트 모양

 

 

Redirection

Communication Channels Redirection
characters
의 미
STDIN 0< 0<< 입력을 키보드가 아닌 파일을 통해 받음
STDOUT 1> 1>> 표준 출력을 터미널이 아닌 파일로 출력
STDERR 2> 2>> 표준 에러 출력을 터미널이 아닌 파일로 출력
&     1>과 2>을 동시에 의미

program &> result.txt
==
program >> result.txt 2>&1


cat /etc/error.txt > /dev/null 2>&1


2>&1  : STDERR을 STDOUT으로 출력

fastwon1@docker-ubuntu:~/ta$ date > date.out   //date명령어를 date.out로 출력
fastwon1@docker-ubuntu:~/ta$ cat date.out 
2021. 08. 30. (월) 06:59:24 KST
fastwon1@docker-ubuntu:~/ta$ date >> date.out //date명령어를 date.out 파일에 append
fastwon1@docker-ubuntu:~/ta$ cat date.out 
2021. 08. 30. (월) 06:59:24 KST
2021. 08. 30. (월) 06:59:36 KST
fastwon1@docker-ubuntu:~/ta$ ls
date.out
fastwon1@docker-ubuntu:~/ta$ ls date.out date.out2
ls: 'date.out2'에 접근할 수 없습니다: 그런 파일이나 디렉터리가 없습니다
date.out
fastwon1@docker-ubuntu:~/ta$ ls date.out date.out2 2> /dev/null  //error메시지를 /dev/null로 버림
date.out  //정상조회만 출력

Redirection

 

 

Pileline

fastwon1@docker-ubuntu:~$ ls -l | wc -l  //현재파일의 수를 출력
31
fastwon1@docker-ubuntu:~$ 
fastwon1@docker-ubuntu:/etc$ cat passwd | cut -d: -f 1 | sort | wc -l //passwd파일을 : 기준으로 나누고 
//첫번째 field를 정렬하여 유저의 수를 출력 
48
fastwon1@docker-ubuntu:/etc$

 

C++ lambda function

 

lambda 문법

 

기본구조

[captures](parameters) -> return type { body }

/*
* captures: comma(,)로 구분된 캡처
* parameters: 함수의 파라미터
* return type: 함수의 반환형
* body: 함수의 몸통
*/

ref: https://www.variadic.xyz/2011/10/12/c11-lambda-having-fun-with-brackets/

[captures]

[] 외부변수를 캡처하지 않음.
[=] 모든 외부변수 복사로 캡처
[=,...] 모든 외부변수 복사 및 가변인자 템플릿
[&] 모든 외부변수 참조로 캡처
[&,...] 모든 외부변수 참조 및 가변인자 템플릿
[this] 현재 객체를 참조로 캡처

[specifier]

mutable 복사로 캡처된 변수를 함수안에서 수정할 수 있게 하는 지정자
constexpr 함수호출 연산자가 상수식(default값)

 

lambda를 사용한 sort함수 예제

#include <iostream>
#include <ctime>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX_ELEM 10
#define RAND_MAX 100
class Test {
public:
	int a;
};
void printElements(vector<Test>& tt) {
	for (const auto& v : tt)
	{
		cout << v.a << ' ';
	}
	cout << endl;
}
void insertElements(std::vector<Test>& v) {
	srand((unsigned int)time(NULL));
	Test a[MAX_ELEM];
	for (int i = 0; i < MAX_ELEM; i++) {
		a[i].a = rand() % RAND_MAX + 1;
		v.push_back(a[i]);
	}
}
int n = 10;
int main() {
	vector<Test> testVector;
	insertElements(testVector);
	int referenceTest = 15;
	cout << "정렬 전: ";
	printElements(testVector);
	// Sort in a ascending order
	{
		sort(testVector.begin(), testVector.end(),
			[=](Test first, Test second) -> bool
			{
				//n = 0; // =로 정의된 캡쳐블록은 read only.
				int a = n;
				return first.a < second.a;
			});
		cout << "정렬 후(오름차순): ";
		printElements(testVector);
		// Sort in a descending order
		sort(testVector.begin(), testVector.end(),
			[&](Test& first, Test& second) -> bool
			{
				n = 10;
				referenceTest = 10; // &로 정의된 캡쳐블록은 write 가능
				return first.a > second.a;
			});
		cout << "정렬 후(내림차순): ";
		printElements(testVector);
	}
	return 0;
}

 

 

 

Class

package com.example.myapplication.kotlin

fun main(array: Array<String>) {
    val smallCar: Car = Car("V8 engine", "small")
    val bigCar = Car("V8 engine", "big")
    val superCar: SuperCar = SuperCar("good engine", "big", "black")
}

class Car(var engine: String, var body: String) {  //constructor 축약버전

}

class SuperCar {
    var engine: String = ""
    var body: String = ""
    var door: String = ""

    constructor(engine: String, body: String, door: String) {
        this.engine = engine
        this.body = body
        this.door = door
    }
}

class Car1 constructor(engine: String, body: String) {
    var door: String = ""

    //생성자
    constructor(engine: String, body: String, door: String) : this(engine, body) {
        this.door = door
    }
}

class Car2 {
    var engine: String = ""
    var body: String = ""
    var door: String = ""

    constructor(engine: String, body: String) {
        this.engine = engine
        this.body = body
    }

    constructor(engine: String, body: String, door: String) {
        this.engine = engine
        this.body = body
        this.door = door
    }
}

class RunnableCar constructor(engine:String,body:String) {
    fun ride() {
        println("탑승")
    }
    fun drive() {
        println("Go")
    }
    fun navi(destination:String) {
        println("$destination 으로 목적지 설정")
    }
}

class RunnableCar2 {
    var engine: String = ""  // default는 public 멤버변수
    var body: String = ""

    constructor(engine: String, body: String) {
        println("RunnableCar2의 생성자가 호출되었습니다.")
        this.engine = engine
        this.body = body
    }
    init { //해당 클래스가 생성되기전(생성자가 호출되기전)에 호출되는 함수 
        println("RunnableCar2의 init함수가 호출되었습니다.")
    }

    fun ride() {
        println("탑승")
    }

    fun drive() {
        println("Go")
    }

    fun navi(destination: String) {
        println("$destination 으로 목적지 설정")
    }
}

class OverloadingTestClass() {
    val a: Int = 10

    fun overloadingTest(a: Int) { //오버로딩
        println("Up")
    }

    fun overloadingTest(a: Int, b: Int) { //오버로딩
        println("Down")
    }
}

class Tv(val channels: List<String>) {

    var onOff: Boolean = false
    var currentChannelNumber = 0
        set(value) { //currentChannelNumber 의 값이 할당될때 호출된다.
            field = value
            //currentChannelNumber = value  -> 해당 부분에서 set함수가 다시 호출되기에 무한루프가 발생한다.
            if (field > channels.size-1) {
                field = 0
            }
            if (field <0) {
               field = channels.size -1
            }
        }
        get() { //currentChannelNumber의 값이 호출될때 실행
            println("호출되었습니다.")
            return field
        }
    fun switch() {
        onOff = !onOff
    }

    fun chennalUp() {
        currentChannelNumber += 1
    }

    fun channelDown() {
        currentChannelNumber -= 1
    }

    fun checkCurrentChannel(): String {
        return channels[this.currentChannelNumber]
    }
}

 

'언어 > Kotlin' 카테고리의 다른 글

Kotlin 반복문  (0) 2021.03.04

for문

package com.example.myapplication.kotlin

fun main(args: Array<String>) {

    val a = mutableListOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9)
	
    //반복방법(1)
    for (item in a) { //List의 각 요소를 순회
    	println(item) //value 출력
    }
    
    // 반복방법(2) 
    for ((index, item) in a.withIndex()) { //List의 각 요소를 순회
        println("Index: $index value: $item") index와 value를 같이 출력
    }
    
    //반복방법(3) Lambda방식
     a.forEach {
        println(it)
    }
    
    //반복방법(4) Lambda방식
    a.forEach {item->   //List의 각 요소를 it라는 이름대신 item을 사용
        println(item)
    }
    
    //반복방법(5) Lambda 방식 
    a.forEachIndexed { index, item ->
        println("Index: $index value: $item") 
    }
    
    //반복방법(6) 
    for (i in 0 until a.size) {
        //until은 마지막을 포함하지 않는다.
        println(a[i])
    }
	
    //반복방법(7)
    for (i in 0 until a.size step (2)) { //step(2)는 index를 2씩 건너뛴다.
        println(a[i])
    }
    
    //반복방법(8)
    for (i in a.size -1 downTo(0)) {
        //index 8부터 index 0까지 출력
        println(a[i])
    }
    
    //반복방법(9)
    for (i in a.size -1 downTo(0) step(2)) {
        //index 8부터 index 0까지 index 2씩 건너뛰면서 출력
        println(a[i])
    }
    
    //반복방법(10)
    for (i in 0..10) {
        // ..은 마지막을 포함한다.
        println(i)
    }
    
}

 

While문

package com.example.myapplication.kotlin

fun main(args: Array<String>) {
	var tmp1: Int = 0
    var tmp2: Int = 4

    while(tmp1<tmp2) { //C언어와 동일
        tmp1++
        println("b")
    }
    
    do {   //C언어와 동일
        println("hello")
        tmp1 ++
    } while(tmp1<tmp2)
}

'언어 > Kotlin' 카테고리의 다른 글

Kotlin class  (0) 2021.03.05

Pure zmq4 based on golang 오픈소스를 활용하여 PUB/SUB을 테스트

  • Publish golang 소스코드 작성
  • Subscription golang 소스코드 작성
  • 테스트

ZeroMq 오픈소스 URL

 

go-zeromq/zmq4

[WIP] Pure-Go implementation of ZeroMQ-4. Contribute to go-zeromq/zmq4 development by creating an account on GitHub.

github.com

download go command

  • go get github.com/go-zeromq/zmq4
package main
import (
        "context"
        "log"
        "time"
        "github.com/go-zeromq/zmq4"
)

func main() {
        log.SetPrefix("psenvpub: ")
        // prepare the publisher
        pub := zmq4.NewPub(context.Background())
        defer pub.Close()

        err := pub.Listen("tcp://*:5563")
        if err != nil {
                log.Fatalf("could not listen: %v", err)
        }

        msgA := zmq4.NewMsgFrom(
                []byte("test1"), //This message has named "test1" key
                []byte("My key is test1"),
        )
        msgB := zmq4.NewMsgFrom(
                []byte("test2"), //This message has named "test2" key
                []byte("my key is test2"),
        )
        for {
                err = pub.Send(msgA)
                if err != nil {
                        log.Fatal(err)
                }
                err = pub.Send(msgB)
                if err != nil {
                        log.Fatal(err)
                }
                time.Sleep(time.Second)
        }
}

publish 테스트코드

package main
import (
        "context"
        "log"
        "github.com/go-zeromq/zmq4"
)

func main() {
        log.SetPrefix("psenvsub: ")
        //  Prepare our subscriber
        sub := zmq4.NewSub(context.Background())
        defer sub.Close()
        err := sub.Dial("tcp://localhost:5563")
        if err != nil {
                log.Fatalf("could not dial: %v", err)
        }
        err = sub.SetOption(zmq4.OptionSubscribe, "test1") //Received only named "test1" key.
        if err != nil {
                log.Fatalf("could not subscribe: %v", err)
        }
        for {
                // Read envelope
                msg, err := sub.Recv()
                if err != nil {
                        log.Fatalf("could not receive message: %v", err)
                }
                log.Printf("[%s] %s\n", msg.Frames[0], msg.Frames[1])
        }
}

Subscription 테스트코드

 

테스트코드의 메시지 송수신 확인

'언어 > Golang' 카테고리의 다른 글

Go 오픈소스를 이용하여 C코드에서 활용 할 수 있는 Library 테스트  (0) 2020.11.23
Golang  (0) 2017.05.22

ZeroMQ Go 오픈소스를 활용하여 C코드에서 사용 할 수 있는 Library 테스트

 

(ZeroMQ callback function)

  • Make a library for using at C code.
  • Make a C code.
  • Build by linking a library to C code.

ZeroMq Opensource URL

 

go-zeromq/zmq4

[WIP] Pure-Go implementation of ZeroMQ-4. Contribute to go-zeromq/zmq4 development by creating an account on GitHub.

github.com

download go command

  • go get github.com/go-zeromq/zmq4
package main
/*
#include <stdio.h>
typedef int (*FuncPtr)(int, int);

static inline int Shoot(FuncPtr func,int a,int b)
{
        func(a,b);
}
*/
import "C"
import (
        "context"
        "github.com/go-zeromq/zmq4"
        "log"
)

//export Rcv
func Rcv(t C.FuncPtr) {   
        log.SetPrefix("psenvsub: ")
        sub := zmq4.NewSub(context.Background())
        defer sub.Close()
        err := sub.Dial("tcp://localhost:5563")
        if err != nil {
                log.Fatalf("could not dial: %v", err)
        }
        err = sub.SetOption(zmq4.OptionSubscribe, "test1") //Received only named "test1" key.
        if err != nil {
                log.Fatalf("could not subscribe: %v", err)
        }
        var a int =0
        var b int =0
        for {
                msg, err := sub.Recv()
                if err != nil {
                        log.Fatalf("could not receive message: %v", err)
                }
                log.Printf("[%s] %s\n", msg.Frames[0], msg.Frames[1])
                C.Shoot(t,C.int(a),C.int(b))

                a+=1
                b+=1
        }
}

func main() {} // 반드시 main function 작성.

library.go(수신용 라이브러리 Go파일)

go tool 명령어를 실행하여 라이브러리 빌드

  • command 실행-> go build -o library.so -buildmode=c-shared library.go
#include <stdio.h>
#include "library.h"

int plus (int first, int second)
{
    printf("first:%d second:%d!!!!!!!!!!!!!!!!!!!!!!!!!!!\n",first,second);
        return first + second;
}

int main()
{
        Rcv(plus);
        return 0;
}

rev.c(라이브러리 callback함수)

gcc를 이용하여 빌드

  • gcc -o rcv ./rcv.c ./library.so

 

 

'언어 > Golang' 카테고리의 다른 글

Pure zmq4 based on golang 오픈소스를 활용하여 PUB/SUB 테스트  (0) 2020.11.23
Golang  (0) 2017.05.22

golang의 기본적인 특징

 

 기본특징

  1. Compile 언어
  2. 시스템 프로그래밍 언어
  3. ARM , X86 완벽 지원
  4. windows, linux, mac 지원
  5. Class 미지원
  6. 상속 및 오버로딩 미지원
  7. GC(Garbage Collector)지원
  8. 포인터는 지원하지만 포인터 연산을 지원하지 않음
  9. 엄격한 타입 변환->타입변환을 명시적으로 하지 않으면 컴파일 에러
  10. 객체지향 언어이기도 하고 객체지향 언어가 아니기도 하다.(인터페이스개념을 지원하므로)->상속을 다른 접근 방식으로 지원

 

 C언어의의 비교

  1. 변수 선언
  2. 세미콜론
  3. { }의 올바른 위치 및 의무적 사용 강제화
  4. while문(Go언어는 while문은 없음->for문으로 사용하도록함)
  5. public, private키워드를 지원(함수나 변수의 첫글자가 대문자인 경우 외부에서 접근가능, 소문자인 경우 접근 불가)
  6. switch->Go언어에서는 switch~case문에서 break가 없음.
  7. Go언어의 function은 2개이상의 값을 return할 수 있다.(경험상 활용도가 높고 유용하다.)
  8. 두 변수의 swap는 간결하다.
    1. ex) i, j = j, i
  9. Go언어에서는 변수 선언후 사용하지 않는 변수가 있을 경우 컴파일 오류 발생
  10. Go 언어에서는 암시적 형변환은 없다.(버그 사전방지효과.)

 

 Go 언어로 개발된 대표적인 상용제품

  1. Docker, Kubernetes
  2. Twitch 서비스(게임 중계 사이트) - 아마존이 1억달러에 인수
    • 채팅 기능을 Go 언어로 개발하여 성공(성능이나 안정성이 향상)
  3. Cisco InterCloud 서비스
    1. Private/Public cloud 연결을 통해 IOT 애플리케이션 런칭을 목표로 하는 서비스
  4. Parse.com
    1. Ruby에서 Golang으로 옮김(성능 확장 개선)
  5. 온라인 결제 페이팔(Paypal)
    1. BLE(Bluetooth Low Energy)관련고크
  6. XOR Exchange, Yext, DataDog, CoreOs, New Relic, SoundCloud, MongoDB, Canonical 등.

+ Recent posts