리디렉션 후 파일이 생성되지 않고 "cp: 계산할 수 없음" 오류가 나타남

리디렉션 후 파일이 생성되지 않고 "cp: 계산할 수 없음" 오류가 나타남

아래 bash 스크립트에서는 파일이 있는지 확인하고, 없으면 파일을 생성한 후 간단한 코드를 작성합니다. 한 번은 작동했지만(이유는 모르겠습니다) 뭔가를 변경한 것 같아서 더 이상 작동하지 않으며 오류가 어디에 있는지 찾을 수 없습니다.

#...

template_file="~/mytest_template.c";

if [[ -z $template_file ]]; then
   echo -e "#include <stdio.h>\n#include <stdlib.h>\n\n\nint main(int argc, char**argv){\n\n\t\n\nreturn 0;\n}" > ~/mytest_template.c;
fi

#sleep 0.5; ---> I tried this too.

cp ~/mytest_template.c mytest.c;

내가 얻는 오류는 다음과 같습니다. cp: cannot stat '/home/username/mytest_template.c': No such file or directory

감사해요.

답변1

if [[ -z $template_file ]]; then

-z연산자는 문자열이 비어 있는지 테스트합니다. 여기서 값은 template_file방금 할당했기 때문에 null이 아닙니다. 따라서 내부 명령이 if실행되지 않습니다.

스크립트가 실행되기 전에 파일이 존재하지 않으면 스크립트가 실행될 때 파일이 존재하지 않습니다 cp.

여기서 무엇을 테스트하려는지 잘 모르겠지만 파일이 존재 하지 않는 경우를 대비해 파일을 생성하려면 ! -f $filename.-f!

또한 할당에서 물결표는 확장되지 않지만 따옴표 안에 있으므로 그대로 유지됩니다.

template_file="~/mytest_template.c";

후속 리디렉션이나 명령 cp에서는 변수를 사용 하지 않으므로 문제가 없습니다.

그래서,

template=~/mytest_template.c
final=~/mytest.c
if [[ ! -f $template ]]; then
    echo "..." > "$template"
fi
cp "$template" "$final"

관련 정보