Reputation: 527
I have some files, like:
FILE1="apple.txt"
FILE2="grapes.txt"
FILE3="strawberry.txt"
How can I make these files in bash?
I tried this, but I got an error...
for f in {1..3}
do
echo hello > $(FILE$f)
done
Errors:
./make_files.sh: line 48: FILE1: command not found
./make_files.sh: line 48: $(FILE$f): ambiguous redirect
I need 3 txts, apple, grapes and strawberry which are contains hello.
Upvotes: 0
Views: 69
Reputation: 12393
IIUC, you want this:
for f in {1..3}
do
echo hello > FILE"$f"
done
EDIT:
Based on your comment to another answer I think you really want this:
for f in {1..3}
do
echo hello > $(< FILE"$f")
done
Example:
$ ls
FILE1 FILE2 FILE3
$ cat FILE1 FILE2 FILE3
apple.txt
grapes.txt
strawberry.txt
$ for f in {1..3}
> do
> echo hello > $(< FILE"$f")
> done
$ cat apple.txt grapes.txt strawberry.txt
hello
hello
hello
Upvotes: 1
Reputation: 95252
Or do it all at once:
for f in FILE{1..3}; do
echo hello >"${!f}"
done
The main error in your code was the$(
...)
, which is command substitution: it was trying to run the namesFILE1
, FILE2
, etc. as commands in order to use the output of those commands as the names of the files to write.
What you want to do instead is use those as parameter names. To indirectly retrieve the value of a parameter whose name is stored in another parameter, you use !
, as in ${!f}
.
But most of the time when you're doing something like this you're better off using an array:
FILES=("apple.txt" "grapes.txt" "strawberry.txt")
for f in "${FILES[@]}"; do
echo hello >"$f"
done
Upvotes: 1
Reputation: 333
I guess what you want do is to create the files with the three name: apple.txt , grapes.txt and strawberry.txt
so you should do:
for f in {1..3}
do
TMP="FILE$f"
echo hello > "${!TMP}"
done
Upvotes: 2