While working on a Bash script today I was working with Claude to help me get the script working. The task was to write some code to identify files with incorrect permissions, and exit with an error code if there were any files. Also, to print the files and their locations.
ChatGPT worked hard on the problem and have many different solutions. Unfortunately, none of them ultimately worked, even when I tried to interject some of my own code to fix the problem.
Claude took a similar approach when it tried to write the code. Maybe I prompted it better this time, but eventually it made the code simpler and decided to add the bad files to an array, and count the improperly permissioned files. Obvious in retrospect that this is the way to get things done.
Claude had an interesting snippet of code that I’ve seen before, but have glazed over when I see it. It was using a find command with a while loop and a read command. I decided to break down the code into something more digestible that I would understand more readily. Here is what I came up with. Claude helped me setup a better delimiter to get it to work.
Attempt 1:
#!/bin/bash
while IFS= read -r -d ' ' file; do
echo "Num is Num: $file"
done < <(echo -n {1..5})
Result:
Num is Num: 1
Num is Num: 2
Num is Num: 3
Num is Num: 4
Attempt 2 (with help from Claude):
I knew that my main issue was the delimiter in the read command. The space as a delimiter would only get me 4. This got me to the eventual solution, which I have added my notes of what this does. Cladue added a null character as a delimiter between each number as its printer.
#!/bin/bash
# Below line reads the items into the loop delimited by null character
while IFS= read -r -d '' file; do
# Echo the items as they’re read in
echo "Num is: $file"
# Use process substitution to perform the task, in this case echo 1 to 5 with a space
done < <(printf '%s\0' {1..5})
Result:
Num is: 1
Num is: 2
Num is: 3
Num is: 4
Num is: 5
Claude controlled for spaces and backslashes in filenames with the original code. Things I would not normally have accounted for, since so often in Linux with like to hope no files ever have a space, or characters that make things difficult to delete.
Here was the explanation provided:
while IFS= read -r -d '' file; do: This is the start of the loop. It reads one line (in this case, one filename) at a time from the input provided by the process substitution.
IFS=Â sets the Internal Field Separator (IFS) to an empty string, which ensures that filenames with spaces are read correctly.
-r prevents backslash escapes from being interpreted.
-d '' tells read to use a null character (\0) as the line delimiter instead of a newline.
file is the variable that will hold the filename read from the input.
#bash