[linux]리눅스: 쉘 스크립트 변수선언 및 문자출력하기


쉘 스크립트를 잘 모르시는 분들은 먼저 아래의 글을 읽으시길 바랍니다.
쉘 스크립트란?: https://daewoonginfo.blogspot.com/2019/04/linux.html

문자 출력하기

"hello world"를 출력하기 위해 hello.sh라는 파일을 만들겠습니다.

$ vi hello.sh

#!/bin/bash
echo "hello world"
printf "hello world"
printf "%s %s" hello world
printf "\n"

출력


echo

문장을 출력하는데 자동으로 줄바꿈("\n")이 됩니다.
Java의 println을 생각하시면 됩니다.

printf

C 언어의 printf를 생각하시면 됩니다.
줄바꿈을 하기 위해 따로 "\n"을 주어야합니다.


변수 선언하기

var_name=value
(변수이름)=(값)

변수 사용시에는 "=" 기호 앞뒤로 공백없이 입력해야합니다. 그래야 대입연산자로 판단되어 변수를 선언할 수 있습니다.

$ vi hello.sh

#!/bin/bash
var=hello
echo $var

※ 쉘에서는 기본적으로 모두 문자열로 처리가 됩니다. "" 처리를 할 필요가 없습니다.

출력





$ vi hello.sh

#!/bin/bash
var=hello world
echo $var

출력


""없이 hello world 형식의 띄어쓰기를 할 경우 world를 command로 인식하여 "world라는 command가 존재하지 않다"며 오류를 발생합니다.
이럴 경우에는 "hello world"로 묶어야합니다.





$ vi hello.sh

#!/bin/bash
num1=123
num2=123
echo $num1 + $num2

출력


쉘에서는 기본적으로 모두 문자열로 처리하기 때문에 let이라는 함수를 사용하여 숫자 계산을 해주어야 합니다.

let

let 명령어는 변수에 대한 산술 연산을 수행합니다.

let 사용법

let a=8+3          # a=11
let a=8-3           # a=5


$ vi hello.sh

#!/bin/bash
num1=123
num2=123

let sum=$num1+$num2
echo sum = $sum

출력



연관문헌

[1] https://daewoonginfo.blogspot.com/2019/04/linux.html(쉘 스크립트란? )
[2] https://daewoonginfo.blogspot.com/2019/04/linux-shell-script-sleep.html(쉘에서 sleep 사용)

참고문헌

[1] https://blog.gaerae.com/2015/01/bash-hello-world.html [2] http://lkrox.blogspot.com/2013/01/blog-post_7498.html [3] https://wiki.kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/internal.html

댓글

이 블로그의 인기 게시물

[opencv-python] 이미지 크기조절(resize) 하는 법

[python]파이썬: csv reader header skip (첫번째 행 무시하기, 안읽기)