[Linux] 22-07-28 TIL

gununoo·2022년 7월 28일
2

Linux

목록 보기
9/10
post-thumbnail

bash 문법

for문

예 1) 디렉토리와 파일 출력하기

#!/bin/bash 

for test in /root/*
do
        if [ -d $test ]
        then
                echo "$test : DIR"
        elif [ -f $test ]
        then
                echo "$test : FILE" 
        fi
done
[root@gunwoo 0728]# ./test1.sh 
/root/0725 : DIR
/root/0726 : DIR
/root/0727 : DIR
/root/0728 : DIR
/root/allvm2 : FILE
/root/anaconda-ks.cfg : FILE
/root/kimchi-2.5.0-0.el7.centos.noarch.rpm : FILE
/root/wok-2.5.0-0.el7.centos.noarch.rpm : FILE

select문

#!/bin/bash 

PS3="선택하세요: "

select menu in "날짜 확인" "경로 확인" "디스크 용량 확인" "종료"
do
        case $menu in
        "날짜 확인")
                date ;;
        "경로 확인")
                pwd ;;
        "디스크 용량 확인")
                df -h ;;
        "종료")
                echo "프로그램이 종료됩니다"
                break ;;
        *)
                echo "잘못된 번호를 선택하셨습니다."
        esac
done
[root@gunwoo 0728]# ./test2.sh 
1) 날짜 확인         3) 디스크 용량 확인
2) 경로 확인         4) 종료
선택하세요: 1
Thu Jul 28 09:37:14 KST 2022
선택하세요: 2
/root/0728
선택하세요: 3
Filesystem                Size  Used Avail Use% Mounted on
devtmpfs                  3.8G     0  3.8G   0% /dev
tmpfs                     3.9G  4.0K  3.9G   1% /dev/shm
tmpfs                     3.9G   12M  3.8G   1% /run
tmpfs                     3.9G     0  3.9G   0% /sys/fs/cgroup
/dev/mapper/centos-root   9.4G  2.8G  6.6G  30% /
/dev/mapper/centos-cloud   61G  7.3G   54G  13% /cloud
/dev/sda1                 950M  196M  755M  21% /boot
tmpfs                     781M     0  781M   0% /run/user/0
선택하세요: 5
잘못된 번호를 선택하셨습니다.
선택하세요: 4
프로그램이 종료됩니다

매개변수

bash에서도 명령어 다음은 매개변수이다. -> 고정일 수도, 가변일 수도 있다.

$*: 전체를 하나의 데이터로 취급한다.

$!: 각각의 데이터를 구분하여 취급한다.

$?: 직전 실행 명령의 결과(종료)코드 -> 0만 참, 나머지는 거짓

$#: 인자의 개수

입력 받기

방법 1)

echo -n "당신의 이름은: "
read name 

방법 2)

read -p "당신의 이름은: " last first 
read -n1 -p "실행할까요? [y/n]: " ans 

-> -n1: 한 글자만 입력 가능
-> 프로그램을 중간에 일시 중지시키고 계속 진행을 요구할 경우 엔터키를 눌러 재개시키도록 만들 때 유용하다.

read -t 3 -p "3초 이내에 대답하세요: " ans 

-> 시간 제한 주기

gawk

[root@gunwoo 0728]# gawk '{print "hello"}'
a
hello
b
hello
c
hello
^C

-> 아무거나 입력하면 "hello" 출력

[root@gunwoo 0728]# cat << EOF > a.txt
> name age addr 
> gildong 24 seoul 
> chulsoo 30 busan
> EOF
[root@gunwoo 0728]# gawk '{print $0}' a.txt
name age addr 
gildong 24 seoul 
chulsoo 30 busan

-> {print $0}은 전체 데이터를 출력

[root@gunwoo 0728]# grep gildong a.txt 
gildong 24 seoul 
[root@gunwoo 0728]# grep gildong a.txt | gawk '{print $3}'
seoul

-> 3번째 column을 출력

[root@gunwoo 0728]# gawk -F: '{print $1}' /etc/passwd | head -3 
root
bin
daemon

-> -F는 임시로 IFS를 설정함

정규표현식

[root@gunwoo 0728]# echo "bts" | gawk '/bt/{print $0}'
bts

-> bt가 있으면 전체 출력

?

[root@gunwoo 0728]# echo "bt" | gawk '/be?t/{print $0}'
bt
[root@gunwoo 0728]# echo "bet" | gawk '/be?t/{print $0}'
bet
[root@gunwoo 0728]# echo "beet" | gawk '/be?t/{print $0}'
[root@gunwoo 0728]# 

-> 바로 앞 글자에 e가 0개 또는 1개 있어야 함

[]

[root@gunwoo 0728]# echo "beet" | gawk '/b[ae]?t/{print $0}'
[root@gunwoo 0728]# echo "bet" | gawk '/b[ae]?t/{print $0}'
bet
[root@gunwoo 0728]# echo "bat" | gawk '/b[ae]?t/{print $0}'
bat
[root@gunwoo 0728]# echo "bt" | gawk '/b[ae]?t/{print $0}'
bt

+

[root@gunwoo 0728]# echo "bt" | gawk '/be+t/{print $0}'
[root@gunwoo 0728]# echo "bet" | gawk '/be+t/{print $0}'
bet
[root@gunwoo 0728]# echo "beet" | gawk '/be+t/{print $0}'
beet
[root@gunwoo 0728]# echo "beeet" | gawk '/be+t/{print $0}'
beeet

-> e가 없어도 되고, 여러개 있어도 된다

{}

[root@gunwoo 0728]# echo "beet" | gawk '/be{2}t/{print $0}'
beet

-> e가 정확히 2번 있어야 한다.

[root@gunwoo 0728]# echo "beet" | gawk '/be{1,2}t/{print $0}'
beet
[root@gunwoo 0728]# echo "bet" | gawk '/be{1,2}t/{print $0}'
bet

-> e가 정확히 1번 또는 2번 있어야 한다.

인터벌

[root@gunwoo 0728]# echo "babt" | gawk '/b[a-z]{1,2}t/{print $0}'
babt

-> 알파벳 소문자가 1개 또는 2개 있어야 한다

[root@gunwoo 0728]# echo "abcd10" | gawk '/[a-z0-9]{5,10}/{print $0}'
abcd10
[root@gunwoo 0728]# echo "abc@10" | gawk '/[a-z0-9]{5,10}/{print $0}'
[root@gunwoo 0728]# echo "abc 10" | gawk '/[a-z0-9]{5,10}/{print $0}'
[root@gunwoo 0728]# echo "@abcd10" | gawk '/[a-z0-9]{5,10}/{print $0}'
@abcd10
[root@gunwoo 0728]# echo "the dog is asleep" | gawk '/cat|dog/{print $0}'
the dog is asleep
[root@gunwoo 0728]# echo "the cat is asleep" | gawk '/cat|dog/{print $0}'
the cat is asleep
[root@gunwoo 0728]# echo "the cat is asleep" | gawk '/[ch]at|dog/{print $0}'
the cat is asleep
[root@gunwoo 0728]# echo "the hat is asleep" | gawk '/[ch]at|dog/{print $0}'
the hat is asleep
[root@gunwoo 0728]# echo "the dog is asleep" | gawk '/[ch]at|dog/{print $0}'
the dog is asleep

-> 가능한 경우는 cat, hat, dog

[root@gunwoo 0728]# echo "Sat" | gawk '/Sat(urday)?/{print $0}'
Sat
[root@gunwoo 0728]# echo "Saturday" | gawk '/Sat(urday)?/{print $0}'
Saturday

-> (urday)가 있어도 되고 없어도 된다

DB

mariadb activate

[root@gunwoo 0728]# systemctl enable mariadb --now 
Created symlink from /etc/systemd/system/mysql.service to /usr/lib/systemd/system/mariadb.service.
Created symlink from /etc/systemd/system/mysqld.service to /usr/lib/systemd/system/mariadb.service.
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@gunwoo 0728]# systemctl status mariadb | grep Active
   Active: active (running) since Thu 2022-07-28 10:31:40 KST; 16s ago

mysql_secure_installation

[root@gunwoo 0728]# mysql_secure_installation 

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 
'OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] 
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] 
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] 
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] 
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] 
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

mysql 접속

[root@gunwoo 0728]# mysql -u root -p1234
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 16
Server version: 10.3.35-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

데이터베이스 생성

MariaDB [(none)]> create database mytest;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| mytest             |
| performance_schema |
+--------------------+
4 rows in set (0.000 sec)

MariaDB [(none)]> use mytest; 
Database changed
MariaDB [mytest]> 

권한 부여

MariaDB [mytest]> grant insert,select,delete,update,create on mytest.* to 'testuser'@'localhost' identified by '1234';
Query OK, 0 rows affected (0.001 sec)

MariaDB [mytest]> grant insert,select,delete,update,create on mytest.* to 'testuser'@'%' identified by '1234';
Query OK, 0 rows affected (0.000 sec)

MariaDB [mytest]> flush privileges; 
Query OK, 0 rows affected (0.001 sec)

MariaDB [mytest]> exit;
Bye

데이터베이스로 접속

[root@gunwoo 0728]# mysql mytest -u testuser -p1234
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.3.35-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [mytest]> 

테이블 생성

MariaDB [mytest]> create table employees (
    -> empid int not null,
    -> lastname varchar(20),
    -> firstname varchar(20), 
    -> salary float,
    -> primary key(empid)
    -> );
Query OK, 0 rows affected (0.006 sec)
MariaDB [mytest]> show tables;
+------------------+
| Tables_in_mytest |
+------------------+
| employees        |
+------------------+
1 row in set (0.001 sec)

MariaDB [mytest]> desc employees;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| empid     | int(11)     | NO   | PRI | NULL    |       |
| lastname  | varchar(20) | YES  |     | NULL    |       |
| firstname | varchar(20) | YES  |     | NULL    |       |
| salary    | float       | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
4 rows in set (0.001 sec)

데이터 삽입

MariaDB [mytest]> insert into employees values (1, '홍', '길동', 3300);
Query OK, 1 row affected (0.001 sec)

MariaDB [mytest]> insert into employees values (2, '김', '철수', 4300);
Query OK, 1 row affected (0.002 sec)

MariaDB [mytest]> insert into employees values (3, '박', '영희', 4500);
Query OK, 1 row affected (0.002 sec)
MariaDB [mytest]> select * from employees;
+-------+----------+-----------+--------+
| empid | lastname | firstname | salary |
+-------+----------+-----------+--------+
|     1 || 길동      |   3300 |
|     2 || 철수      |   4300 |
|     3 || 영희      |   4500 |
+-------+----------+-----------+--------+
3 rows in set (0.000 sec)

MariaDB [mytest]> exit;
Bye
[root@gunwoo 0728]# which mysql 
/usr/bin/mysql

quiz. /usr/test 디렉토리를 PATH 변수에 포함시키세요

mkdir /usr/test 
echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
PATH=$PATH:/home:/var
[root@localhost ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/test

참고: https://zetawiki.com/wiki/%EB%A6%AC%EB%88%85%EC%8A%A4_PATH_%EC%B6%94%EA%B0%80

db 조회

[root@gunwoo ~]# mysql mytest -u root -p1234 -e 'select * from employees'
+-------+----------+-----------+--------+
| empid | lastname | firstname | salary |
+-------+----------+-----------+--------+
|     1 || 길동      |   3300 |
|     2 || 철수      |   4300 |
|     3 || 영희      |   4500 |
+-------+----------+-----------+--------+

-e: execute

데이터 삽입 프로그램

#!/bin/bash 

if [ $# -ne 4 ] # 매개변수의 개수가 4개가 아니라면
then
		# 비정상 입력인 경우 
        echo "잘못된 입력 발견: (사용법) -> ./test2.sh 번호 성 이름 연봉"
else
        # 정상 입력인 경우 
        mysql mytest -u root -p1234 -e "insert into employees values ($1, '$2', '$3', $4)"

        # 데이터의 입력 결과 확인 
        if [ $? -eq 0 ]
        then
                echo "데이터 입력 성공"
        else
                echo "데이터 입력 실패"
        fi
fi

확인

[root@gunwoo 0728]# ./test2.sh 5 박 문수 5000
데이터 입력 성공
[root@gunwoo 0728]# mysql mytest -u root -p1234 -e 'select * from employees'
+-------+----------+-----------+--------+
| empid | lastname | firstname | salary |
+-------+----------+-----------+--------+
|     1 || 길동      |   3300 |
|     2 || 철수      |   4300 |
|     3 || 영희      |   4500 |
|     5 || 문수      |   5000 |
+-------+----------+-----------+--------+
[root@gunwoo 0728]# ./test2.sh 5 이 둘리 5000
ERROR 1062 (23000) at line 1: Duplicate entry '5' for key 'PRIMARY'
데이터 입력 실패
[root@gunwoo 0728]# 

-> 중복 id 입력하여 primary duplicated 오류 발생

quiz. 사용자 id는 수동으로 직접 선택하지 말고, RANDOM을 이용하여 10000 ~ 20000 사이에서 선택하도록 하고 이를 DB로 전달한다.
단, 처음 프로그램이 실행되면 해당 번호가 DB에 존재하는지 여부를 먼저 확인(select로 쿼리)하고 이미 존재한다면 번호 랜덤으로 재선택.

#!/bin/bash

empid=''
result=''

if [ $# -ne 3 ]
then
        echo "잘못된 입력 발견 : (사용법) -> ./test2.sh 성 이름 연봉"
else

        while [ 1 ]
        do
                empid=$((RANDOM%10001+10000))
                result=$(mysql mytest -u root -p1234 -e "select empid from employees where empid='$empid'")

                if [ -z $result ]
                then
                        mysql mytest -u root -p1234 -e "insert into employees values ($empid, '$1', '$2', $3)"
                        echo "FINISHED"
                        break
                fi
                continue
        done
fi

RANDOM

[root@gunwoo 0728]# echo $RANDOM 
1366

-> 0 ~ 32767의 임의의 포트 번호를 출력

[root@gunwoo 0728]# echo $((RANDOM % 10 + 1))
9

-> 1부터 10까지

[root@gunwoo 0728]# echo $((RANDOM % 11 + 100))
107

-> 100부터 110까지

[root@gunwoo 0728]# echo $((RANDOM % 101 + 200))
240

-> 200부터 300까지

echo $((RANDOM %10001 + 10000))

함수

  • 다른 언어와 동일하게 미리 지정된 코드를 호출하여 사용하는 것
  • 코드를 간결하게 할 수 있다.

방법 1)

function name {
	필요한 명령들 
}

방법 2)

name () {
	필요한 명령들 
} 

함수 내의 변수명과 함수 밖의 변수명이 동일하다면 이는 병일한 변수인가?
bash는 기본적으로 동일한 변수다.

예)

#!/bin/bash

# 함수 선언 
addem() {
        if [ $# -eq 0 ] || [ $# -gt 2 ] # 매개 변수가 없거나 세 개 이상 입력됨 
        then
                echo "잘못된 입력: 하나 또는 두 수를 입력하세요."
        elif [ $# -eq 1 ] # 매개 변수가 하나 입력됨 
        then
                echo $[ $1 + $1 ]
        else # 매개 변수가 두 개 입력됨 
                echo $[ $1 + $2 ]
        fi
}

# 메인 코드 
echo -n "10 과 20의 합: " 
result1=$(addem 10 20)
echo $result1 

echo -n "10을 10과 더하면?: "
result2=$(addem 10)
echo $result2
[root@gunwoo 0728]# ./test4.sh 
1020의 합: 30
1010과 더하면?: 20

배열

배열은 변수 하나에 다수의 값을 포함시킬 수 있는 방법
bash는 1차원 배열만 지원한다.

[root@gunwoo 0728]# mytest=(one two three four five)
[root@gunwoo 0728]# echo $mytest
one
[root@gunwoo 0728]# echo ${mytest[0]}
one
[root@gunwoo 0728]# echo ${mytest[1]}
two
[root@gunwoo 0728]# echo ${mytest[-1]}
five
[root@gunwoo 0728]# echo ${mytest[*]}
one two three four five

값 수정

[root@gunwoo 0728]# mytest[2]=seven
[root@gunwoo 0728]# echo ${mytest[*]}
one two seven four five

값 제거

[root@gunwoo 0728]# unset mytest[2]
[root@gunwoo 0728]# echo ${mytest[*]}
one two four five
[root@gunwoo 0728]# echo ${mytest[2]}

[root@gunwoo 0728]# 

배열 제거

[root@gunwoo 0728]# unset mytest
[root@gunwoo 0728]# echo ${mytest[*]}

[root@gunwoo 0728]# 

라이브러리 만들기(사용자 모듈)

mylib 라이브러리 파일 생성

#/bin/bash 

addem() {
        echo $[ $1 + $2 ]
}

multem() {
        echo $[ $1 * $2 ]
}

mylib 라이브러리 파일 불러와서 사용하기

#!/bin/bash 

. ./mylib

value1=10
value2=20

result1=$(addem $value1 $value2)
echo $result1 

result2=$(multem $value1 $value2)
echo $result2
[root@gunwoo 0728]# ./test10.sh 
30
200

dialog

yum -y install dialog 

msgbox

dialog --title "test" --msgbox "hello all" 10 20 

10 -> 높이
20 -> 너비

yesno

dialog --title "선택하세요" --yesno "is it ok?" 0 0

yes 선택)

[root@gunwoo 0728]# echo $?
0

no 선택)

[root@gunwoo 0728]# echo $?
1

inputbox

dialog --title "name" --inputbox "what is your name?" 10 20 > name.txt 

-> 실행이 안 된다.

dialog --title "name" --inputbox "what is your name?" 10 20 2> name.txt 

-> 실행이 된다.
-> 2: 표준 오류
-> ok는 0 (표준 입력), cancel은 1(표준 출력) 이므로 2(표준 에러)로 처리함

[root@gunwoo 0728]# echo $?
0
[root@gunwoo 0728]# cat name.txt
이건우

-> 입력 받은 값 확인

[root@gunwoo 0728]# name=$(cat name.txt)
[root@gunwoo 0728]# echo $name
이건우

-> 입력값 변수에 담아서 활용하기 -> 귀찮음
-> mktemp를 이용하면 임시 파일을 만들 수 있다.

textbox

dialog --textbox name.txt 10 20 

-> name.txt의 내용을 출력

[root@gunwoo 0728]# dialog --title "test title" \
> --menu "what is your favorite sports?" 0 0 0 \
> 1 "baseball" 2 "football" 3 "running" \
> 2> sports.txt

-> 높이, 너비, 행
-> 2번 선택 후 OK

[root@gunwoo 0728]# cat sports.txt
2

fselect

dialog --title "파일 선택" --fselect /root/ 0 0 2> dd.txt 

-> 원하는 파일을 고른 후 스페이스바를 누르면 경로가 입력됨
-> 경로 입력 후 OK

[root@gunwoo 0728]# cat dd.txt 
/root/.bashrc

향후 공부해볼 것)
nfv/sdn orchestration + ansible
sdn -> mininet
https://simpleisit.tistory.com/37

profile
take a look

2개의 댓글

comment-user-thumbnail
2022년 7월 28일

고양이가 너무 귀여워요

1개의 답글