-4

I've just started to use linux and bash. I wanted to know how to create a bash function that can add all the files that end with .conf that any user could read into a file. And for the files that a normal user cannot read to be added into another file. Im running it like this, but im getting this error code 4: Syntax error: "(" unexpected (expecting "}") '''

add_files () {
    readable_file_list=()
    unreadable_file_list=()

    # Find all files with .conf extension
    for file in /*.conf; do
        # Check if file is readable by any user
        if [[ -r "$file" ]]; then
            # Add file to readable list
            readable_file_list+=("$file")
        else
            # Add file to unreadable list
            unreadable_file_list+=("$file")
        fi
    done

    # Add readable files to readable_files.txt
    printf '%s\n' "${readable_file_list[@]}" > readable_files.txt

    # Add unreadable files to unreadable_files.txt
    printf '%s\n' "${unreadable_file_list[@]}" > unreadable_files.txt
}

'''

Any ideas on why?

  • Use the `find` command with `-name` to match the filename and `-perm` to test permissions. – Barmar Mar 30 '23 at 23:40
  • The most likely cause of the problem is that you are trying to run the code with `sh` instead of `bash`. – pjh Mar 31 '23 at 01:22
  • Does this answer your question? [Difference between sh and Bash](https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash) – pjh Mar 31 '23 at 01:22
  • Note that `[[ -r $file ]]` only tests if the file is readable by the *current* user. A file can be readable by the current user but not by other users. Note also that readability of a file by users also depends on readability of directories on the file's path in the file system. – pjh Mar 31 '23 at 01:27

1 Answers1

1

Here is the function:

function add_files {
    readable_file_list=()
    unreadable_file_list=()

    # Find all files with .conf extension
    for file in /path/to/directory/*.conf; do
        # Check if file is readable by any user
        if [[ -r "$file" ]]; then
            # Add file to readable list
            readable_file_list+=("$file")
        else
            # Add file to unreadable list
            unreadable_file_list+=("$file")
        fi
    done

    # Add readable files to readable_files.txt
    printf '%s\n' "${readable_file_list[@]}" > readable_files.txt

    # Add unreadable files to unreadable_files.txt
    printf '%s\n' "${unreadable_file_list[@]}" > unreadable_files.txt
}
Muhammed Jaseem
  • 782
  • 6
  • 18