본문 바로가기
CS/Shell scripts

[Bash] 쉘 스크립트 출력 시 개행이 안되는 경우 해결방법

by Warehaus 2021. 6. 24.

Bash 를 사용하면서 각총 명령의 출력을 변수에 잠시 넣었다가 다시 출력해서 가공하는 경우가 있다.

이런 경우 echo $변수명 을 많이 사용하게 되는데, 그냥 명령어를 쳤을 때에는 개행이 되는데 변수에 넣고나니 개행이 안되었다.

이리저리 찾아보다가 아래와 같은 해결방법을 찾았는데 내용은 다음과 같다.

문제 : 파일을 cat으로 출력해서 변수에 저장 후 echo로 다시 출력하는 경우, 결과가 상이함.

 

[ test 파일 ]

1
2
3
4
5
6
7
8
9
10

 

[ script 파일 ]

#!/usr/bin/bash

cat test

output=`cat test`

echo $output

 

[ 출력결과 ]

1
2
3
4
5
6
7
8
9
10
1 2 3 4 5 6 7 8 9 10

 

해결 : double quotation으로 변수를 감싼 뒤 출력해 준다.

#!/usr/bin/bash

cat test

output=`cat test`

echo "$output"

 

[ 결과 ]

1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10

 

앞과 뒤 결과가 일치함을 보여준다.

 

아래는 Bash manual 에 있는 내용이다. 이 해결방법과 관련 된 내용이니 참고하면 좋겠다.

출처 : http://www.gnu.org/software/bash/manual/html_node/Quoting.html

3.1.2.2 Single Quotes
Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes
Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.
The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).