Also, I out-of-hand reject any criticism of an AI that specifies only the brand ("ChatGPT") and not the specific model version, settings, etc...
So, for example, Gemini 2.5 Pro (Jan 2025) with temperature 0.15 prompted with: "Write a short, idiomatic bash script that takes a file containing a list of directory names, changes to each one, runs a command, and then returns to the original working directory."
Spits out this:
#!/bin/bash
# A script to run a command in a list of directories.
# Exit if the wrong number of arguments are provided.
if [[ $# -lt 2 ]]; then
echo "Usage: $0 <file_with_dirs> <command> [args...]" >&2
exit 1
fi
DIR_FILE="$1"
shift # The rest of the arguments ("$@") are now the command.
# Ensure the directory list file exists and is readable.
if [[ ! -r "$DIR_FILE" ]]; then
echo "Error: Cannot read file '$DIR_FILE'" >&2
exit 1
fi
# Read the file line by line.
while IFS= read -r dir; do
# Skip empty lines or non-existent directories.
if [[ -n "$dir" && -d "$dir" ]]; then
echo "==> Entering '$dir'..."
# Run command in a subshell to keep the 'cd' local.
# '&&' ensures the command only runs if 'cd' succeeds.
(cd "$dir" && "$@")
echo "<== Finished with '$dir'."
else
echo "--> Skipping invalid directory: '$dir'" >&2
fi
done < "$DIR_FILE"
echo "All done."
That worked for me, but I was testing it in WSL 2 where I got a gibberish error... which was because I edited the file in Windows Notepad and the line endings were confusing bash. Gemini helpfully told me how to fix that too!Something that I found amusing, and again, is a criticism of bash instead of the AI, is that this fails to process the last line if it isn't terminated with a \n character.
PS: This is almost a one-liner in PowerShell, and works with or without the final terminator character:
Push-Location
Get-Content dirs.txt | cd -PassThru | Foreach-Object { echo "Hello from: $pwd" }
Pop-Location
Gemini also helped me code-golf this down to: pushd;gc dirs.txt|%{cd $_;"Hello from: $pwd"};popd