1

I am making a template shell script for a project, one function that is a must is the ability to make a copy of a template configuration file as a new file. However, this is not going to be handled statically, I make and set a runtime variable ($modloader) that comes from the shell scripts file name and copies the template as this same name. I did some tests with static file names and cp works fine, but seems to fall apart when checking if the file is already present (line 5). If I run this in the terminal, it does not see the file it is checking for. I believe it is looking for it in a more literal context and doesn't 'understand' it's using a variable.

#!/bin/sh

modloader=basename -s .sh "$0"

if "./Settings/$modloader.ini"; then cp "./Settings/Template.ini" "./Settings/$modloader.ini" fi

Mr. Mendelli
  • 1,468

1 Answers1

1

seems to fall apart when checking if the file is already present

I don't see you're checking if the file is already present. Your if "./Settings/$modloader.ini"; tries to run the ini file. In general it may be a valid test for something, if the file is designed to be run like this and to return exit status according to what you want to test.

Even if running the file in question was possible, it would make no sense to make the file a tester of its own (non)existence.

The right way in a shell to tell if the file exists is:

test -e "./Settings/$modloader.ini"
# or equivalently
[ -e "./Settings/$modloader.ini" ]

Notes:

  • test -e tests for a file of any type.
  • test -e or such will give you a false negative (i.e. non-zero exit status) if permissions for some relevant directory (e.g. Settings in your case) don't allow checking if the file exists.

Additionally you want to negate the test. The line in your code would be like:

if ! [ -e "./Settings/$modloader.ini" ]; then

if is not necessary though. GNU cp with -n (--no-clobber) may be all you need in place of this if … fi of yours. The option is not portable and you most likely want another non-portable option -T (--no-target-directory) in case the target turns out to be (a symlink to) a directory.

cp -nT "./Settings/Template.ini" "./Settings/$modloader.ini"

Note if the target already exists and thus cp -n is a no-op, the exit status will be 0. You will get the same exit status if the target doesn't exist and copying succeeds. This means if you want to do more (than cp) depending on whether the file existed or not, you need prior if anyway.