posted by 귀염둥이채원 2021. 4. 15. 10:25

 

---------------------------------------------------------

# Syntax of while loop:

---------------------------------------------------------

while [ condition ]; do

commands

done

 

---------------------------------------------------------

# 고정 횟수만큼 반복

---------------------------------------------------------

#!/bin/bash

n=1

while [ $n -le 5 ]; do

echo "Running $n time"

((n++))

done

 

# output

$ bash test.sh

Running 1 time

Running 2 time

Running 3 time

Running 4 time

Running 5 time

 

---------------------------------------------------------

# while에서 break 사용

---------------------------------------------------------

#!/bin/bash

n=1

while [ $n -le 10 ]; do

if [ $n == 6 ]; then

echo "terminated"

break

fi

echo "Position: $n"

((n++))

done

 

# output

$ bash test.sh

Position: 1

Position: 2

Position: 3

Position: 4

Position: 5

terminated

 

---------------------------------------------------------

# while에서 continue 사용

---------------------------------------------------------

#!/bin/bash

n=0

while [ $n -le 5 ]; do

((n++))

 

if [ $n == 3 ]; then

continue

fi

echo "Position: $n"

 

done

 

# output

$ bash test.sh

Position: 1

Position: 2

Position: 4

Position: 5

Position: 6

 

---------------------------------------------------------

# 무한루프

---------------------------------------------------------

#!/bin/bash

n=1

while :; do

printf "The current value of n=$n\n"

if [ $n == 3 ]; then

echo "good"

elif [ $n == 5 ]; then

echo "bad"

elif [ $n == 7 ]; then

echo "ugly"

elif [ $n == 10 ]; then

exit 0

fi

((n++))

done

 

# output

$ bash test.sh

The current value of n=1

The current value of n=2

The current value of n=3

good

The current value of n=4

The current value of n=5

bad

The current value of n=6

The current value of n=7

ugly

The current value of n=8

The current value of n=9

The current value of n=10

 

posted by 귀염둥이채원 2021. 4. 15. 09:43

 

---------------------------------------------------------

# Syntax of for loop:

---------------------------------------------------------

for variable_name in lists; do

commands

done

 

---------------------------------------------------------

# 정적 값 읽기

---------------------------------------------------------

#!/bin/bash

 

for color in Blue Green Pink White Red; do

echo "Color = $color"

done

 

# output

$ bash test.sh

Color = Blue

Color = Green

Color = Pink

Color = White

Color = Red

 

for i in 1 2 3 4 5; do

echo "Welcome $i times"

done

 

# output

$ bash test.sh

Welcome 1 times

Welcome 2 times

Welcome 3 times

Welcome 4 times

Welcome 5 times

 

---------------------------------------------------------

# 배열 변수 읽기

---------------------------------------------------------

#!/bin/bash

ColorList=("Blue Green Pink White Red")

for color in $ColorList; do

if [ $color == 'Pink' ]; then

echo "My favorite color is $color"

fi

done

 

# output

$ bash test.sh

My favorite color is Pink

 

---------------------------------------------------------

# 명령 줄 인수 읽기

---------------------------------------------------------

#!/bin/bash

for myval in $*; do

echo "Argument: $myval"

done

 

# output

$ bash test.sh hello world shell

Argument: hello

Argument: world

Argument: shell

 

---------------------------------------------------------

# 홀수 및 짝수 찾기

---------------------------------------------------------

#!/bin/bash

for ((n = 1; n <= 5; n++)); do

if (($n % 2 == 0)); then

echo "$n is even"

else

echo "$n is odd"

fi

done

 

# output

$ bash test.sh

1 is odd

2 is even

3 is odd

4 is even

5 is odd

 

---------------------------------------------------------

# 구구단 출력

---------------------------------------------------------

#!/bin/sh

 

if [ $# -eq 0 ]; then

echo "Error - Number missing form command line argument"

echo "Syntax : $0 number"

echo "Use to print multiplication table for given number"

exit 1

fi

 

n=$1

 

for (( i = 0; i <= 9; i++ )); do

#for i in 1 2 3 4 5 6 7 8 9; do

echo "$n * $i = $(expr $i \* $n)"

done

 

# output

$ bash test.sh 3

3 * 0 = 0

3 * 1 = 3

3 * 2 = 6

3 * 3 = 9

3 * 4 = 12

3 * 5 = 15

3 * 6 = 18

3 * 7 = 21

3 * 8 = 24

3 * 9 = 27

 

---------------------------------------------------------

# for문 range 설정

---------------------------------------------------------

#!/bin/bash

for i in {1..10}; do

echo $i

done

 

# output

$ bash test.sh

1

2

3

4

5

6

7

8

9

10

 

---------------------------------------------------------

# ls 결과 출력하기

---------------------------------------------------------

#!/bin/bash

for i in $(ls); do

echo $i

done

 

# output

$ bash test.sh

01_tip.sh

02_print.sh

03_variable.sh

 

posted by 귀염둥이채원 2021. 4. 15. 08:10

 

---------------------------------------------------------

# Syntax of while case:

---------------------------------------------------------

* case 문은 "case"로 시작하고 "esac"로 끝납니다.

* ")"는 패턴을 종료하는 데 사용됩니다.

* 명령이 있는 패턴은 절이라고하며 모든 절은 (;;)로 끝납니다.

* 별표 기호 *를 사용하여 기본 대소 문자를 정의 할 수 있습니다.

* case 문은 먼저 입력된 $ ariable을 다른 패턴과 일치시킵니다.

패턴이 일치하면 이중 세미콜론 (;;)까지 해당하는 명령 집합이 실행됩니다.

* 정규식을 지원하며 | 기호로 다중 값을 입력 가능하며 조건의 문장 끝에는 ;; 기호로 끝을 표시한다

* 대문자와 소문자는 구별한다.

 

case $variable in

pattern-1)

commands

;;

pattern-2)

commands

;;

pattern-3)

commands

;;

pattern-N)

commands

;;

*)

commands

;;

esac



조건에 다중 값을 사용하고 싶다면 "|" 연산자를 사용한다.

case $variable in

pattern-1 | pattern-2)

commands

....

....

;;

pattern-3 | pattern-4)

commands

....

....

;;

 

---------------------------------------------------------

# 월 이름이 일치하면 해당 월의 해당 이벤트를 표시

---------------------------------------------------------

* "shopt -s nocasematch"는 대소 문자에 관계없이 패턴을 일치시키는 데 사용됩니다.

 

#!/bin/bash

 

shopt -s nocasematch

printf "Enter name of the month: "

read month

 

case $month in

January)

echo " 24th January international Day of Education."

;;

February)

echo " 20 FebruaryWorld Day of Social Justice ."

;;

March)

echo "8th March International women’s day."

;;

April)

echo "7th April The World Health Day"

;;

*)

echo "No matching information found"

;;

esac

 

# output

$ bash test.sh

Enter name of the month: February

20 FebruaryWorld Day of Social Justice

 

$ bash test.sh

Enter name of the month: April

7th April The World Health Day

 

$ bash test.sh

Enter name of the month: april

7th April The World Health Day

 

$ bash test.sh

Enter name of the month: Undefine

No matching information found

 

---------------------------------------------------------

# 국가에 수도 출력

---------------------------------------------------------

#!/bin/bash

shopt -s nocasematch

echo -n "Enter the name of a country: "

read country

 

echo -n "The capital of $country is "

case $country in

UK | "United Kingdom")

echo -n "London"

;;

Turkey)

echo -n "Ankara"

;;

USA)

echo -n "Washington DC"

;;

*)

echo -n "Information not available"

;;

esac

echo ""

 

# output

$ bash test.sh

Enter the name of a country: USA

The capital of USA is Washington DC

 

---------------------------------------------------------

# case문 테스트를 위한 반복문

---------------------------------------------------------

#!/bin/bash

for string in "HELLO" "WORLD" "hello" "world" "s" "start" "end" "etc"; do

 

# case문 시작

case ${string} in

hello | HELLO)

echo "${string}: hello 일때"

;;

wo*)

echo "${string}: wo로 시작하는 단어 일때"

;;

s | start)

echo "${string}: s 혹은 start 일때"

;;

e | end)

echo "${string}: e 혹은 end 일때"

;;

*)

echo "${string}: 기타"

;;

esac

# //case문 끝

 

done

 

# output

$ bash test.sh

HELLO: hello 일때

WORLD: 기타

hello: hello 일때

world: wo로 시작하는 단어 일때

s: s 혹은 start 일때

start: s 혹은 start 일때

end: e 혹은 end 일때

etc: 기타

 

---------------------------------------------------------

# 참고 사이트

---------------------------------------------------------

https://blog.gaerae.com/2015/01/bash-hello-world.html

 

posted by 귀염둥이채원 2021. 4. 15. 06:23

 

---------------------------------------------------------

# if 기본 구문

---------------------------------------------------------

if [ Condition ]

then

< Statement >

fi

 

# 조건문

# AND

if [ ${string1} == ${string2} ] && [ ${string3} == ${string4} ]

..생략

 

# OR

if [ ${string1} == ${string2} ] || [ ${string3} == ${string4} ]

..생략

 

# 다중 조건

if [[ ${string1} == ${string2} || ${string3} == ${string4} ]] && [ ${string5} == ${string6} ]

..생략



---------------------------------------------------------

# Simple Bash if/else statement

---------------------------------------------------------

#!/bin/bash

printf "Enter a number: "

read number

 

if [ $number -lt 100 ]; then

"echo “Your entered number is less than 100"

fi

 

# output

$ bash if.sh

Enter a number: 10

“Your entered number is less than 100”

 

$ bash if.sh

Enter a number: 100

 

---------------------------------------------------------

# Simple Bash if/else statement

---------------------------------------------------------

#!/bin/bash

directory="./BashScripting"

 

# bash check if directory exists

if [ -d $directory ]; then

echo "Directory exists"

else

echo "Directory does not exists"

fi

 

# output

$ bash test.sh

Directory does not exists

 

---------------------------------------------------------

# if-elif-else

---------------------------------------------------------

#!/bin/bash/

printf "Enter a number from 1-20: "

read number

if [ $number -lt 10 ]; then

echo "Your entered number is less than 10"

elif [ $number -le 20 ]; then

echo "Your entered number is greater than 10"

else

echo "You entered number is not between 1-20"

fi

 

# output

$ test.sh

Enter a number from 1-20: 4

Your entered number is less than 10

 

$ bash test.sh

Enter a number from 1-20: 14

Your entered number is greater than 10

 

$ bash test.sh

Enter a number from 1-20: 30

You entered number is not between 1-20

 

---------------------------------------------------------

# Nested if/else

---------------------------------------------------------

#!/bin/bash

choice=4

 

# Print to stdout

echo "1. Bash"

echo "2. Scripting"

echo "3. Tutorial"

echo -n "Please choose a word [1,2 or 3]? "

 

# Loop while the variable choice is equal 4

# bash while loop

while [ $choice -eq 4 ]; do

# read user input

read choice

 

# bash nested if/else

if [ $choice -eq 1 ]; then

echo "You have chosen word: Bash"

else

if [ $choice -eq 2 ]; then

echo "You have chosen word: Scripting"

else

if [ $choice -eq 3 ]; then

echo "You have chosen word: Tutorial"

else

echo "Please make a choice between 1-3 !"

echo "1. Bash"

echo "2. Scripting"

echo "3. Tutorial"

echo -n "Please choose a word [1,2 or 3]? "

choice=4

fi

fi

fi

done

 

# output1

$ bash test.sh

1. Bash

2. Scripting

3. Tutorial

Please choose a word [1,2 or 3]? 1

You have chosen word: Bash

 

# output2

$ bash test.sh

1. Bash

2. Scripting

3. Tutorial

Please choose a word [1,2 or 3]? 2

You have chosen word: Scripting

 

# output3

$ bash test.sh

1. Bash

2. Scripting

3. Tutorial

Please choose a word [1,2 or 3]? 3

You have chosen word: Tutorial

 

---------------------------------------------------------

# OR 조건 (||)

---------------------------------------------------------

#!/bin/bash/

printf "Enter a number: "

read number

if [ $number -le 10 ] || [ $number -le 20 ]; then

echo "You have entered the correct number"

else

echo "Your entered the incorrect number"

fi

 

# output

$ bash test.sh

Enter a number: 5

You have entered the correct number

 

$ bash test.sh

Enter a number: 13

You have entered the correct number

 

$ bash test.sh

Enter a number: 70

Your entered the incorrect number

 

---------------------------------------------------------

# Mathematical Operators

---------------------------------------------------------

#!/bin/bash

 

if [ $1 -gt 0 ]; then

echo "$1 > 0"

fi

 

if [ $1 -ge 0 ]; then

echo "$1 >= 0"

fi

 

if [ $1 -eq 0 ]; then

echo "$1 == 0"

fi

 

if [ $1 -ne 0 ]; then

echo "$1 != 0"

fi

 

if [ $1 -lt 0 ]; then

echo "$1 < 0"

fi

 

if [ $1 -le 0 ]; then

echo "$1 <= 0"

fi

 

# output

$ bash test.sh -3

-3 != 0

-3 < 0

-3 <= 0

 

$ bash test.sh 5

5 > 0

5 >= 0

5 != 0

 

$ bash test.sh 0

0 >= 0

0 == 0

0 <= 0

 

---------------------------------------------------------

# String Operators

---------------------------------------------------------

#!/bin/bash

string_null=""

string1="string1"

 

if [ $string_null -n ]; then

echo "not null string"

else

echo "null string"

fi

 

if [ $string_null -z ]; then

echo "null string"

else

echo "not null string"

fi

 

if [ "$string_null" == "$string1" ]; then

echo "strings equal"

else

echo "strings not equal"

fi

 

if [ "$string_null" != "$string1" ]; then

echo "strings not equal"

else

echo "strings equal"

fi

 

# output

$ bast test.sh

not null string

null string

strings not equal

strings not equal

 

---------------------------------------------------------

# Test for files and directories

---------------------------------------------------------

#!/bin/bash

 

if [ -s $1 ]; then

echo "$1 not empty file"

fi

 

if [ -f $1 ]; then

echo "$1 normal file. Not a directory"

fi

 

if [ -e $1 ]; then

echo "$1 exists"

fi

 

if [ -d $1 ]; then

echo "$1 is directory and not a file"

fi

 

if [ -r $1 ]; then

echo "$1 is read-only file"

fi

 

if [ -x $1 ]; then

echo "$1 is executable"

fi

 

# output

$ bash test.sh test.sh

test.sh not empty file

test.sh normal file. Not a directory

test.sh exists

 

---------------------------------------------------------

# if…else…fi

---------------------------------------------------------

#!/bin/sh

if [ $# -eq 0 ]; then

echo "$0 : You must give/supply one integers"

exit 1

fi

 

if [ $1 -gt 0 ]; then

echo "$1 number is positive"

else

echo "$1 number is negative"

fi

 

# output

$ bash test.sh

test.sh : You must give/supply one integers

 

$ bash test.sh 1

1 number is positive

 

$ bash test.sh -1

-1 number is negative

 

$ bash test.sh 100 100 100

100 number is positive

 

---------------------------------------------------------

# 참고사이트

---------------------------------------------------------

https://devhints.io/bash

http://programmingexamples.wikidot.com/bash-scripting

https://blog.gaerae.com/2015/01/bash-hello-world.html

'쉘스크립트' 카테고리의 다른 글

[Shell Script] 반복문(for)  (0) 2021.04.15
[Shell Script] 조건문(case)  (0) 2021.04.15
[Shell Script] read를 이용한 입력값 받기  (0) 2021.04.15
[Shell Script] 배열(Array)  (0) 2021.04.15
[Shell Script] 인자(Argument)  (0) 2021.04.15
posted by 귀염둥이채원 2021. 4. 15. 05:57

---------------------------------------------------------

# 간단한 읽기 명령 예시

---------------------------------------------------------

#!/bin/bash

# echo -n 옵션은 줄바꿈을 하지 않는다.

echo -n "What is your favorite food : "

read answer

echo "Oh! you like $answer!"

 

# echo는 줄바꿈 한다.

echo "What is your favorite food : "

read answer

echo "Oh! you like $answer!"

 

# printf는 줄바꿈을 하지 않는다.

printf "What is your favorite food : "

read answer

echo "Oh! you like $answer!"

 

# printf에서 "\n"을 사용하여 줄바꿈한다.

printf "What is your favorite food : \n"

read answer

echo "Oh! you like $answer!"

 

# output

$ bash test.sh

What is your favorite food : pizza

Oh! you like pizza!

What is your favorite food :

piaaz

Oh! you like piaaz!

What is your favorite food : pizza

Oh! you like pizza!

What is your favorite food :

pizza

Oh! you like pizza!

 

---------------------------------------------------------

# 옵션과 함께 읽기 명령 사용

---------------------------------------------------------

* -p 옵션은 입력과 관련된 사용자에게 유용한 메시지를 표시

* -s 옵션은 사용자가 입력 할 터미널에서 텍스트를 숨기는 데 사용

 

#!/bin/bash

# Type your Login Information

read -p 'Username: ' user

read -sp 'Password: ' pass

 

if (($user == "admin" && $pass == "12345")); then

echo -e "\nSuccessful login"

else

echo -e "\nUnsuccessful login"

fi

 

# output

$ bash test.sh

Username: admin

Password:

Successful login

 

---------------------------------------------------------

# 읽기 명령을 사용하여 여러 입력 가져 오기

---------------------------------------------------------

#!/bin/bash

# Taking multiple inputs

echo -n "Type four names of your favorite programming languages: "

read lan1 lan2 lan3 lan4

echo "$lan1 is your first choice"

echo "$lan2 is your second choice"

echo "$lan3 is your third choice"

echo "$lan4 is your fourth choice"

 

# output

$ bash test.sh

Type four names of your favorite programming languages: python java go javascript

python is your first choice

java is your second choice

go is your third choice

javascript is your fourth choice

 

---------------------------------------------------------

# 시간 제한이있는 읽기 명령 사용

---------------------------------------------------------

* -t옵션을 사용한 사용자에 대한 시간 제한 설정 (초단위)

* 사용자가 5 초 내에 데이터를 입력 할 수 없으면 프로그램은 값없이 종료

#!/bin/bash

read -t 5 -p "Type your favorite color : " color

echo $color

 

# output

$ bash test.sh

Type your favorite color : white

white

 

---------------------------------------------------------

# 간단한 메뉴를 생성하고 선택된 메뉴 항목 에 따라 조치를 취하는 스크립트

---------------------------------------------------------

#!/bin/bash

while :; do

clear

echo "-------------------------------------"

echo " Main Menu "

echo "-------------------------------------"

echo "[1] Show Todays date/time"

echo "[2] Show files in current directory"

echo "[3] Show calendar"

echo "[4] Start editor to write letters"

echo "[5] Exit/Stop"

echo "======================="

echo -n "Enter your menu choice [1-5]: "

read yourch

case $yourch in

1)

echo "Today is $(date) , press a key. . ."

read

;;

2)

echo "Files in $(pwd)"

ls -l

echo "Press a key. . ."

read

;;

3)

cal

echo "Press a key. . ."

read

;;

4) vi ;;

5) exit 0 ;;

*)

echo "Opps!!! Please select choice 1,2,3,4, or 5"

echo "Press a key. . ."

read

;;

esac

done

 

# output

$ bash test.sh

-------------------------------------

Main Menu

-------------------------------------

[1] Show Todays date/time

[2] Show files in current directory

[3] Show calendar

[4] Start editor to write letters

[5] Exit/Stop

=======================

Enter your menu choice [1-5]: 1

Today is 2021년 4월 10일 토요일 03시 58분 48초 KST , press a key. . .

 

---------------------------------------------------------

# 참고 사이트

---------------------------------------------------------

https://linuxhint.com/bash-script-user-input/

'쉘스크립트' 카테고리의 다른 글

[Shell Script] 조건문(case)  (0) 2021.04.15
[Shell Script] 조건문(if-elif-else)  (0) 2021.04.15
[Shell Script] 배열(Array)  (0) 2021.04.15
[Shell Script] 인자(Argument)  (0) 2021.04.15
[Shell Script] 변수(Variable)  (0) 2021.04.15
posted by 귀염둥이채원 2021. 4. 15. 04:42

 

---------------------------------------------------------

# array example

---------------------------------------------------------

#!/bin/bash

# 배열의 크기 지정없이 배열 변수로 선언

# 참고: 'declare -a' 명령으로 선언하지 않아도 배열 변수 사용 가능함

declare -a array

 

# 4개의 배열 값 지정

array=("hello" "test" "array" "world")

 

# 기존 배열에 1개의 배열 값 추가(순차적으로 입력할 필요 없음)

array[4]="variable"

 

# 기존 배열 전체에 1개의 배열 값을 추가하여 배열 저장(배열 복사 시 사용)

array=(${array[@]} "string")

 

# 위에서 지정한 배열 출력

echo "hello world 출력: ${array[0]} ${array[3]}"

echo "배열 전체 출력: ${array[@]}"

echo "배열 전체 개수 출력: ${#array[@]}"

 

printf "배열 출력: %s\n" ${array[@]}

 

# 배열 특정 요소만 지우기

unset array[4]

echo "배열 전체 출력: ${array[@]}"

 

# 배열 전체 지우기

unset array

echo "배열 전체 출력: ${array[@]}"

 

# output

$ bash test.sh

hello world 출력: hello world

배열 전체 출력: hello test array world variable string

배열 전체 개수 출력: 6

배열 출력: hello

배열 출력: test

배열 출력: array

배열 출력: world

배열 출력: variable

배열 출력: string

배열 전체 출력: hello test array world string

배열 전체 출력:

 

---------------------------------------------------------

# array example

---------------------------------------------------------

#!/bin/bash

MyArray=(HTML Javascript CSS JQuery Bootstrap)

 

# Print 5 values individually

echo "----------Print 5 values individually---------------"

echo ${MyArray[0]}

echo ${MyArray[1]}

echo ${MyArray[2]}

echo ${MyArray[3]}

echo ${MyArray[4]}

 

#Print all values by using *

echo "-----------------Print all values-------------------"

echo ${MyArray[*]}

 

# output

$ bash test.sh

----------Print 5 values individually---------------

HTML

Javascript

CSS

JQuery

Bootstrap

-----------------Print all values-------------------

HTML Javascript CSS JQuery Bootstrap

 

---------------------------------------------------------

# array에서 for문 사용

---------------------------------------------------------

#!/bin/bash

MyArray=(HTML Javascript CSS JQuery Bootstrap)

 

for i in "${MyArray[@]}"; do

#echo $i

if [[ "$i" == "CSS" ]]; then

echo $i

fi

done

 

# output

$ bash test.sh

CSS

 

---------------------------------------------------------

# array에서 for문 사용

---------------------------------------------------------

#!/bin/bash

# Declare array with 4 elements

ARRAY=('Debian Linux' 'Redhat Linux' Ubuntu Linux)

 

# get number of elements in the array

ELEMENTS=${#ARRAY[@]}

 

# echo each element in array

# for loop

for ((i = 0; i < $ELEMENTS; i++)); do

echo ${ARRAY[${i}]}

done

 

# output

$ bash test.sh

CSS

 

# output

# bash test.sh

Debian Linux

Redhat Linux

Ubuntu

Linux

 

---------------------------------------------------------

# 배열 요소 추가

---------------------------------------------------------

#!/bin/bash

MyArray=(HTML Javascript CSS JQuery Bootstrap)

 

# array append

MyArray+=("Go")

 

# Add new element at the end of the array

MyArray[${#MyArray[@]}]="Python"

 

# 한줄로 표시

for val in "${MyArray[@]}"; do echo $val; done

 

# output

$ bash test.sh

HTML

Javascript

CSS

JQuery

Bootstrap

Go

Python

 

---------------------------------------------------------

# 배열 끝에 여러 요소 추가

---------------------------------------------------------

#!/bin/bash

# Declare two string arrays

arrVar1=("John" "Watson" "Micheal" "Lisa")

arrVar2=("Ella" "Mila" "Abir" "Hossain")

 

# Add the second array at the end of the first array

arrVar=(${arrVar1[@]} ${arrVar2[@]})

 

# Iterate the loop to read and print each array element

for value in "${arrVar[@]}"; do

echo $value

done

 

# output

$ bash test.sh

John

Watson

Micheal

Lisa

Ella

Mila

Abir

Hossain

 

---------------------------------------------------------

# 참고사이트

---------------------------------------------------------

https://blog.gaerae.com/2015/01/bash-hello-world.html

https://linuxhint.com/bash_append_array/

 

posted by 귀염둥이채원 2021. 4. 15. 04:11

---------------------------------------------------------

# argument example

---------------------------------------------------------

#!/bin/bash

# echo arguments to the shell

echo $1 $2 $3 ' -> echo $1 $2 $3'

 

# We can also store arguments from bash command line in special array

args=("$@")

 

# echo arguments to the shell

echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'

 

# use $@ to print out all arguments at once

echo $@ ' -> echo $@'

 

# use $# variable to print out

# number of arguments passed to the bash script

echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'

 

# with for

for i in $@; do

echo "$i"

done

 

# output

$ bash test.sh input1 input2 input3 input4 input5

input1 input2 input3 -> echo $1 $2 $3

input1 input2 input3 -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}

input1 input2 input3 input4 input5 -> echo $@

Number of arguments passed: 5 -> echo Number of arguments passed: $#

input1

input2

input3

input4

input5

 

posted by 귀염둥이채원 2021. 4. 15. 03:32

---------------------------------------------------------

# 변수(Variable)

---------------------------------------------------------

* 변수 사용시에는 "=" 기호 앞뒤로 공백이 없이 입력하면 대입연산자가 된다.

* 선언된 변수는 기본적으로 전역 변수(global variable)다.

- 함수 안에서만 지역 변수(local variable) 사용할 있는데 사용할려면 변수 앞에 local을 붙여주면 된다.

* 전역 변수는 현재 실행된 스크립트 파일에서만 유효하다.

- 자식 스크립트에서는 사용 없는 변수다.

* 변수명 앞에 export을 붙여주면 환경 변수(environment variable)로 설정되어 자식 스크립트에서 사용 가능하다.

* 환경 변수 사용시 예약 변수(reserved variable)에 주의하자.

(참고로 환경 변수는 .bash_profile에서 정의한다.)

 

---------------------------------------------------------

# 전역변수와 지역변수

---------------------------------------------------------

#!/bin/bash

# 전역 변수 지정

string="hello world"

echo ${string}

 

# 지역 변수 테스트 함수

string_test() {

# 전역 변수와 동일하게 사용함. 만약 local 뺀다면 전역 변수에 덮어씌어지게 됨

local string="local"

echo ${string}

}

# 지역 변수 테스트 함수 호출

string_test

# 지역 변수 테스트 함수에서 동일한 변수 명을 사용했지만 값이 변경되지 않음

echo ${string}

 

# 환경 변수 선언

export hello_world="hello world..."

# 자식 스크립트 호출은 스크립트 경로을 쓰면된다.

/home/export_test.sh

 

# 환경 변수를 테스트하기 위해 export_test.sh 파일을 만들고 선언한 변수를 확인해본다.

echo ${hello_world}

 

# output

$ ash test.sh

hello world

local

hello world

test.sh: line 19: /home/export_test.sh: No such file or directory

hello world...

 

---------------------------------------------------------

# 전역변수와 지역변수

---------------------------------------------------------

#!/bin/bash

# This variable is global and can be used anywhere in this bash script

VAR="global variable"

function bash {

# Define bash local variable

# This variable is local to bash function only

local VAR="local variable"

echo $VAR

}

echo $VAR

bash

# Note the bash global variable did not change

# "local" is bash reserved word

echo $VAR

 

# output

$ bash test.sh

global variable

local variable

global variable

 

---------------------------------------------------------

# 참고 사이트

---------------------------------------------------------

https://blog.gaerae.com/2015/01/bash-hello-world.html

 

posted by 귀염둥이채원 2021. 4. 15. 02:44

---------------------------------------------------------

# echo 옵션

---------------------------------------------------------

-n: 마지막에 따라오는 개행 문자(newline) 문자를 출력하지 않음

-e: 문자열에서 역슬래시(\)와 조합되는 이스케이프 문자(escape sequence)를 문자로 인식

 

---------------------------------------------------------

# echo와 printf를 이용한 출력

---------------------------------------------------------

#!/bin/bash

 

echo ""

echo "echo-----------"

# 줄바꿈한다.

echo "hello world"

# -n옵션 사용시 개행 문자(newline) 문자를 출력하지 않음

echo -n "hello world"

 

echo ""

echo "print-----------"

# 개행 문자(newline) 문자를 출력하지 않음

printf "hello world"

printf "%s %s" hello world

 

# "\n"을 사용하여 줄바꿈한다.

printf "%s %s\n" hello world

 

# output

$ bash test.sh

 

echo-----------

hello world

hello world

print-----------

hello worldhello worldhello world

 

---------------------------------------------------------

# echo에서 -e 옵션 사용 예시

---------------------------------------------------------

#!/bin/bash

# -e 옵션 없음

echo "1\n2\n3\n"

 

# -e 옵션 있음

echo -e "1\n2\n3\n"

 

# -e 옵션 있음

echo -e "1\t2\t3\t"

 

# output

$ bash test.sh

1\n2\n3\n

1

2

3

 

1 2 3

 

---------------------------------------------------------

# echo에서 -e 옵션 사용 예시

---------------------------------------------------------

#!/bin/bash

 

# -e 옵션은 escape 문자를 사용가능하게 합니다.

echo -e "1234567890"

 

# new line

echo -e "123

456

789

0"

 

# tab

echo -e "123 456 789 0"

 

# \v vertical tab

echo -e "123\v456\v789\v0"

 

# \c 이후 내용 생략, new line 포함

echo -e "123456\c7890"

 

# output

$ bash test.sh

123457890

123

456

789

0

123 456 789 0

123

456

789

0

123456

 

posted by 귀염둥이채원 2021. 4. 15. 02:41

---------------------------------------------------------

# 스크립트 실행 방법

---------------------------------------------------------

echo "hello world"

printf "hello world"

printf "%s %s" hello world

 

가지 방법으로 bash 파일을 실행 가능

# 첫번째 방법

$ bash test.sh

 

# 두번째 방법

$ chmod a+x test.sh

$ ./ test.sh

 

---------------------------------------------------------

# 주석처리

---------------------------------------------------------

#!/bin/bash

val=25

 

# Comment - print value

echo $val

 

# Multiline comment

: '

multiline comment

multiline comment

multiline comment

multiline comment

multiline comment

'

echo $val

 

# output

$ bash test.sh

25

25

 

---------------------------------------------------------

# 스크립트 auto indent (줄맞춤)

---------------------------------------------------------

# vim에서 gg=G를 입력한다.

gg - go to beginning of the file

G - go to end of the file

= - indent

 

# vimrc 설정

set sw=4

filetype indent on

 

# Reference

https://unix.stackexchange.com/questions/19945/auto-indent-format-code-for-vim

https://www.unix.com/unix-for-dummies-questions-and-answers/87221-vi-auto-indent-whole-file-once.html

 

# vscode에서 plugin을 설치

Shift + Option + F

 

# Reference

https://marketplace.visualstudio.com/items?itemName=foxundermoon.shell-format

https://marketplace.visualstudio.com/items?itemName=shakram02.bash-beautify

 

---------------------------------------------------------

# 쉘스크립트 문법 체크

---------------------------------------------------------

아래 사이트에서 문법이 잘못된 부분을 체크해준다.

https://www.shellcheck.net/

 

---------------------------------------------------------

# 디버깅 - set 옵션들 (-e, -u, -x)

---------------------------------------------------------

set은 쉘의 옵션을 설정하는 명령어이다.

-e, -u 옵션을 설정하면 스크립트에서 문제가 발생한것을 찾을수 있다.

* -e: 쉘 스크립트 실행 중에 0이 아닌 값으로 exit을 한 명령이 있으면 나머지 스크립트를 실행하지 않은 채 exit한다.

* -u: 정의되지 않은 변수(undefined)를 참조하면 에러를 출력하며 바로 exit한다.

* -x: 쉘 스크립트가 실행하는 모든 명령을 화면에 출력한다. 디버깅에 유용하다.

 

# 쉘스크립트의 도입부에 다음과 같이 적으면 된다.

set -e -u -x

 

# bash xxx.sh 실행시 옵션 적용

bash -x xxx.sh

bash -eux xxx.sh

 

---------------------------------------------------------

# shell command 실행

---------------------------------------------------------

#!/bin/bash

# use backticks " ` ` " to execute shell command

echo `date`

 

# executing bash command without backticks

echo date

 

# use #(command)

echo $(date)

 

# shell execution

echo "I'm in $(pwd)"

echo "I'm in `pwd`"

 

# output

$ bash test.sh

2021410일 토요일 041028초 KST

date

2021410일 토요일 041028초 KST

I'm in /src/shell

I'm in /src/shell

 

---------------------------------------------------------

# 스크립트 디렉토리와 이름 출력

---------------------------------------------------------

#!/bin/bash

# Get the location where this script is located since it may have been run from any folder

scriptFolder=$(cd $(dirname "$0") && pwd)

# Also determine the script name, for example for usage and version.

# - this is useful to prevent issues if the script name has been changed by renaming the file

scriptName=$(basename $scriptFolder)

 

echo "scriptFolder: $scriptFolder"

echo "scriptName: $scriptName"

 

# output

$ bash test.sh

scriptFolder: /Users/src/shell

scriptName: test.sh

 

---------------------------------------------------------

# 마지막 작업의 종료 상태 확인

---------------------------------------------------------

#!/bin/bash

# The following will always fail because the file does not exist.

fileToRemove="/tmp/some-file-that-does-not-exist"

 

# Redirect error to /dev/null so script message is used instead.

rm "$fileToRemove" 2> /dev/null

if [ $? -eq 0 ]; then

echo "Success removing file: $fileToRemove"

else

echo "File does not exist: $fileToRemove"

fi

 

# output

$ bash test.sh

File does not exist: /tmp/some-file-that-does-not-exist

 

---------------------------------------------------------

# 학습자료들

---------------------------------------------------------

# 핵심 요약 자료

https://blog.gaerae.com/2015/01/bash-hello-world.html

http://programmingexamples.wikidot.com/bash-scripting

https://linuxconfig.org/bash-scripting-tutorial

 

# cheetsheet

https://devhints.io/bash

 

# tutorial

https://linuxhint.com/30_bash_script_examples/

https://linuxconfig.org/bash-scripting-tutorial

http://learn.openwaterfoundation.org/owf-learn-linux-shell/useful-scripts/useful-scripts/

 

# template

https://betterdev.blog/minimal-safe-bash-script-template/

https://github.com/ralish/bash-script-template/blob/main/template.sh

https://natelandau.com/boilerplate-shell-script-template/

https://jonlabelle.com/snippets/view/shell/another-bash-script-template

http://mars.tekkom.dk/w/index.php/Bash_script_template

https://dev.to/thiht/shell-scripts-matter

 

# example

https://www.tecmint.com/linux-server-health-monitoring-script/

 

# youtube

https://www.youtube.com/watch?v=RIKJVIcYNqE&list=PLYRfEO8DA8gikpkXw8wF8kJZDod2lFrML&index=1

https://www.youtube.com/watch?v=08XnZ8YA8MU&list=PLTJfebMjBKSLv0yQrgCOBLZtvBBD5lWqu&index=1

https://www.youtube.com/watch?v=035pZp2R50M

https://www.youtube.com/watch?v=RdY7wiCPN-Q

https://www.youtube.com/watch?v=GtovwKDemnI

https://www.youtube.com/watch?v=e7BufAVwDiM

https://www.youtube.com/watch?v=cQepf9fY6cE&list=PLS1QulWo1RIYmaxcEqw5JhK3b-6rgdWO_

 

# 참고 자료

http://mug896.github.io/bash-shell/

https://linuxhint.com/category/bash-programming/

https://github.com/awesome-lists/awesome-bash

https://github.com/alebcay/awesome-shell

https://awesomerank.github.io/lists/alebcay/awesome-shell.html