개발/Linux

Bash Shell 입출력 (echo, read, printf)

달리초이 2023. 1. 2. 11:31


[목차]

1. echo

2. read

3. printf


1. echo

prints text to standard output

echo <옵션> <메시지>

-n : 메시지 출력 후 newline 문자를 추가하지 않는다.

-e : backslash escapes문자를 해석하여 특별한 의미를 지정한다.

\t : TAB키
\n: 줄 바꿈
\a: alert(bell)

- 예시

echo "Your time is up"
echo "Your time is up" > time.txt
echo -n "Name:"
echo -e "First\tSecond"

score=90
echo score
# score
echo $score
# 90

 

 

 

2. read

reads text from standard input

read <옵션> 변수명

-n : 지정한 문자수만큼 입력 받는다.

-t : 지정된 시간 안에 입력 받는다.

-s : silent mode로 입력하는 글자가 보이지 않는다.

- read 명령에서 변수 명 생략 시 기본 REPLY 변수에 채워진다.

- 예시

read name
read -t10 -n8 password
read -t10 -n8 -s password
read
echo -n "Name: "; read name
echo $name

read name score
# kim 80 classA
echo $name
# kim
echo $score
# 80 classA

echo -n "your name: " ; read name
# your name: _

echo -n "continue(y/n)?" ; read answer
# continue(y/n)? _

 

 

 

3. printf

서식 format에 맞춰서 출력할 수 있는데, C언어의 printf 함수와 동일

printf format <메시지>

%d or %i : 숫자

%s : 문자열

%f : 실수형 숫자

- 예시

printf "Hello linux shell\n"
# Hello linux shell

printf "Name: %s \t Score: %i\n" jack 90
# Name: jack       Score: 90

today=`date +%Y%m%d`
printf "date is %s\n" $today
# date is 20230102

printf "number is %.3f\n" 20
# number is 20.000

printf "|%10s|%10s|%10.2f\n" ubuntu jack 10
# |    ubuntu|      jack|     10.00

printf "|%-10s|%-10s|%10.2f\n" ubuntu jack 10
# |ubuntu    |jack      |     10.00
cat > input-exam.sh
#!/bin/bash
#: Usage	: input-exam.sh
echo -n "Input a directory name : "
read dirname
echo "=========================================="
date +%Y-%m-%d
echo "=========================================="
du -sh $dirname 2> /dev/null
echo

chmod +x input-exam.sh

 

 

- 문제풀이: shell script 작성

1) 대화식으로 사용자에게 디렉토리 이름을 입력 받으시오.

2) 입력한 디렉토리의 모든 파일 목록을 /tmp/날짜.txt 파일에 저장하기.

cat > lab3.sh
#!/bin/bash
echo "Input directory name: "
read dirname
ls $dirname > /tmp/$(date +%Y%m%d).txt

chmod +x lab3.sh

 

 

 

 

- 출처 : 따배셸

7. Input&Output

https://youtu.be/jzcE4vCg1sU

728x90
반응형