Reputation: 45
I have some files in a folder with content as a 4 digit number in each file. How can I export variable name=filename
and its value=filecontent
with a loop in bash?
Upvotes: 0
Views: 1164
Reputation: 6995
It is quite simple.
#!/bin/bash
dir="."
for file in "$dir"/*
do
[[ -f "$file" ]] || continue
var="${file##*/}"
if
printf -v "$var" "$(<"$file")" 2>/dev/null
then
export "$var"
else
echo "Invalid filename: $file"
fi
done
Not all filenames are valid variable names. You would need to either make 100% sure all files you could ever use your script with have names that are valid variable names, or (preferably) perform some kind of test or error handling. The script above will detect a failed assignment, but will not do anything to clever aside from complaining.
Some explanations...
The loop body is skipped if the file is not a regular file (i.e. directory, special files are skipped).
The code uses the -v
option of printf
, which causes printf
to assign a value whose name is provided instead of printing to stdout. This is safer than, say, improperly using eval
, which would open up code injection possibilities, especially considering you are using filenames which the script cannot control.
The "$(<"$file")"
statement is a command substitution that outputs the content of the file, like a redirection that produces a string rather than a stream.
Finally, please note that if you want to export
the variables in preparation for other things your script will do, you are fine. However, if you want to export these variables to the shell that calls the script, you will need to execute the script with .
(or source
), because a child process can never export (or make any kind of assignment) to the variables of its parent. Sourcing causes the shell to read the commands from the stated file without starting a child process.
Upvotes: 4