변수 값에 따라 작업을 수행하는 Bash 스크립트가 있습니다. case 문의 일반 구문은 다음과 같습니다.
case ${command} in
start) do_start ;;
stop) do_stop ;;
config) do_config ;;
*) do_help ;;
esac
명령이 제공되지 않고 do_help
명령이 인식되지 않는 경우 기본 루틴을 실행하고 싶습니다 . 따라서 케이스 값을 생략하려고했습니다.
case ${command} in
) do_default ;;
...
*) do_help ;;
esac
결과는 예측 가능했습니다.
syntax error near unexpected token `)'
그런 다음 정규식을 사용해 보았습니다.
case ${command} in
^$) do_default ;;
...
*) do_help ;;
esac
이것으로 빈 케이스 ${command}
가 떨어집니다 *
.
불가능한 일을하려는 건가요?
답변
이 case
명령문은 정규식이 아닌 glob을 사용하고 정확한 일치를 주장합니다.
따라서 빈 문자열은 평소와 같이 ""
또는 ''
다음 과 같이 작성됩니다 .
case "$command" in
"") do_empty ;;
something) do_something ;;
prefix*) do_prefix ;;
*) do_other ;;
esac
답변
나는 간단한 폴 스루를 사용합니다. 전달 된 매개 변수 ($ 1 = “”)가 두 번째 case 문에서 포착되지 않지만 다음 *는 알 수없는 매개 변수를 포착합니다. “”) 및 *)를 뒤집 으면 *)처럼 작동하지 않습니다.이 경우 공백을 포함하여 매번 모든 것을 포착합니다.
#!/usr/local/bin/bash
# testcase.sh
case "$1" in
abc)
echo "this $1 word was seen."
;;
"")
echo "no $1 word at all was seen."
;;
*)
echo "any $1 word was seen."
;;
esac
답변
내가하는 방법은 다음과 같다.
#!/bin/sh
echo -en "Enter string: "
read string
> finder.txt
echo "--" >> finder.txt
for file in `find . -name '*cgi'`
do
x=`grep -i -e "$string" $file`
case $x in
"" )
echo "Skipping $file";
;;
*)
echo "$file: " >> finder.txt
echo "$x" >> finder.txt
echo "--" >> finder.txt
;;
esac
done
more finder.txt
수십 개의 cgi 파일을 포함하는 파일 시스템에서 하나 또는 두 개의 파일에 존재하는 서브 루틴을 검색하는 경우 ‘ssn_format’과 같은 검색어를 입력합니다. bash는 다음과 같은 텍스트 파일 (finder.txt)로 결과를 반환합니다.
-./registry/master_person_index.cgi : SQLClinic :: Security :: ssn_format ($ user, $ script_name, $ local, $ Local, $ ssn) if $ ssn ne “”;