0

I make an array of files as follows, and then "source" those files. I am also trying to make a script as close to POSIX possible so I don't have issues running it in different shells.

set -- path alias function
for file in "${@}"; do
    [ -r "${SELF_PATH_DIR}.${file}" ] && [ -f "${SELF_PATH_DIR}.${file}" ] && . "${SELF_PATH_DIR}.${file}";
done

It works, but I don't like the fact that I have to specify ${SELF_PATH_DIR}. many times, so that the string takes the real path to the files (/Users/karlsd/dotfiles/.path, etc.).

Is there any way to make it simpler? For example, to add /Users/karlsd/dotfiles/. to each item before the loop?

2 Answers 2

3

Just assign "${SELF_PATH_DIR}.${file}" to a temporary variable or modify the same variable.

By the way: If the loop is the only spot where you are using set --/$@ then you can iterate directly over the list:

for file in path alias function; do
    file="${SELF_PATH_DIR}.${file}"
    [ -r "$file" ] && [ -f "$file" ] && . "$file";
done
Sign up to request clarification or add additional context in comments.

Comments

0

You actually have a potentially larger problem than a mere repetition of the variables: If one of the entries in $@ happens to be the absolute path to some file, your code would break.

I would use realpath inside the loop:

absfile=$(realpath "$file")
[ -r "$absfile" ] && [ -f "$absfile" ] && . "$absfile" 

Of course this would silently skip "buggy" entries of file, for instance if the name denotes a directory instead of a plain file or those you have no read access. Unless this is the desired behaviour, I would omit the tests and just source the file. If things aren't right, you get at least an explicit error message.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.