문자열이 비어 있지 않거나 쉘 스크립트에서 공백이 아닌지 확인하십시오.
문자열이 공백도 비어 있지 않은지 확인해야하는 다음 셸 스크립트를 실행하려고합니다. 그러나 언급 된 3 개의 모든 문자열에 대해 동일한 출력을 얻고 있습니다. "[["구문도 사용해 보았지만 아무 소용이 없습니다.
내 코드는 다음과 같습니다.
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str"!=" " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2"!=" " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3"!=" " ]; then
echo "Str3 is not null or space"
fi
다음 출력이 표시됩니다.
# ./checkCond.sh
Str is not null or space
Str2 is not null or space
의 양쪽에 공백이 필요합니다 !=
. 코드를 다음과 같이 변경하십시오.
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str" != " " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2" != " " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3" != " " ]; then
echo "Str3 is not null or space"
fi
쉘에서 빈 문자열을 확인하기 위해
if [ "$str" == "" ];then
echo NULL
fi
또는
if [ ! "$str" ];then
echo NULL
fi
단일 공백이 아닌 임의의 공백을 확인해야하는 경우 다음을 수행 할 수 있습니다.
여분의 공백 문자열을 제거하려면 (중간 공백을 하나의 공백으로 간주) :
trimmed=`echo -- $original`
The --
ensures that if $original
contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put ""
around $original
, or the spaces will not get removed.
After that you can just check if $trimmed
is empty.
[ -z "$trimmed" ] && echo "empty!"
Another quick test for a string to have something in it but space.
if [[ -n "${str// /}" ]]; then
echo "It is not empty!"
fi
"-n" means non-zero length string.
Then the first two slashes mean match all of the following, in our case space(s). Then the third slash is followed with the replacement (empty) string and closed with "}". Note the difference from the usual regular expression syntax.
You can read more about string manipulation in bash shell scripting here.
To check if a string is empty or contains only whitespace you could use:
shopt -s extglob # more powerful pattern matching
if [ -n "${str##+([[:space:]])}" ]; then
echo '$str is not null or space'
fi
See Shell Parameter Expansion and Pattern Matching in the Bash Manual.
[ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty"
Stripping all newlines and spaces from the string will cause a blank one to be reduced to nothing which can be tested and acted upon
'Programing' 카테고리의 다른 글
crontab을 통해 Python 스크립트 실행 (0) | 2020.10.07 |
---|---|
Vim Surround는 단어 주위에 추가 공간을 삽입합니다. (0) | 2020.10.07 |
앱 그룹을 사용하여 앱간에 데이터 통신 및 유지 (0) | 2020.10.07 |
C ++에서 쉼표 연산자의 다른 동작이 반환됩니까? (0) | 2020.10.07 |
Google Play 앱 서명을 활성화하는 방법 (0) | 2020.10.07 |