There is list.txt with list of files separated by newline: file1.txt file2.txt file3.txt…
- User
There is list.txt with list of files separated by newline: file1.txt file2.txt file3.txt
Write bash script to read files list from file and run command for each file
- Assistant
Certainly! Here's a simple bash script that reads each filename from
list.txtand runs a command for each file. Replaceyour_commandwith the command you want to run:bash#!/bin/bash while IFS= read -r file; do # Check if the line is not empty if [[ -n "$file" ]]; then echo "Processing file: $file" your_command "$file" fi done < list.txtExplanation:
while IFS= read -r file; do: reads each line fromlist.txtinto the variablefile.[[ -n "$file" ]]checks if the line is not empty.your_command "$file"runs the command on each file.- The input to the loop comes from
list.txtvia< list.txt.
Example:
If you want to
cateach file, modifyyour_commandtocat:bash - User
i don't need to input file name. File name already in variable $list="list.txt"
- Assistant
Got it! If you have the filename stored in a variable, e.g.,
bashlist="list.txt"you can reference the variable in the script like this:
bash#!/bin/bash list="list.txt" while IFS= read -r file; do # Skip empty lines if [[ -n "$file" ]]; then echo "Processing file: $file" your_command "$file" fi done < "$list"Explanation:
list="list.txt"— filename is stored in variablelistdone < "$list"— reads from the file stored in the variable$list
Example with
cat:bash#!/bin/bash list="list.txt" while IFS= read -r file; do if [[ -n "$file" ]]; then echo "Contents of $file:" cat "$file" fi done < "$list"Use
"$list"as the input for thewhileloop.Let me know if you want it customized!