0

In the bash script below, I check whether a file exists or not and then if it doesn't, I create it and write a simple snippet to it. It worked once(I don't know why), but I guess I have changed something and it's no more working, I can't find where's my mistake:

#...

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;

The error I get is this: cp: cannot stat '/home/username/mytest_template.c': No such file or directory

Thanks.

aderchox
  • 691

1 Answers1

1
if [[ -z $template_file ]]; then

The -z operator tests if a string is empty. Here, the value of template_file isn't empty, since you just assigned to it. Hence the command inside the if doesn't run.

If the file didn't exist before the script was run, it won't exist at the time of the cp either.

I'm not sure what you're trying to test here, but if you want to create the file in case it doesn't exist, then you want to use ! -f $filename. -f tests if a file exists, and ! inverts the test.

Also note that in the assignment, the tilde isn't expanded, but left as-is, since it's within quotes:

template_file="~/mytest_template.c";

You're not using that variable in the subsequent redirection, or in the cp command, so you don't get issues from that.

So,

template=~/mytest_template.c
final=~/mytest.c
if [[ ! -f $template ]]; then
    echo "..." > "$template"
fi
cp "$template" "$final"
ilkkachu
  • 138,973
  • Thanks a lot! Why are "$file"s in double quotes? – aderchox Feb 19 '19 at 20:10
  • (By the way, It's just a script for my temporary tests while doing C. There is a function called "ctest" which can be called with one of the "create", "compile", "run", "clear" commands, e.g "ctest create", thanks once again). – aderchox Feb 19 '19 at 20:12
  • 2
    @Moytaba, the quotes are necessary when the variables contain whitespace or wildcards (*?[]). That's not the case here, but it's still a good habit to get into quoting them. See, e.g. When is double-quoting necessary? and http://mywiki.wooledge.org/WordSplitting – ilkkachu Feb 19 '19 at 20:13