0

I'm wanting to move many files, each of which are in their own directory, into one common directory. Each of the directories that these files are in have the same basename as the files. I've created a text fill listing all of these basenames. I then made a sript file written as:

#!/bin/bash

for i in 'cat basenames.txt'
do
        cd $i
        mv ${i}.html /c/Users/USER/directory1
        cd ..

done

When I run the script I get :

move.sh: line 4: cd: too many arguments
mv: cannot stat 'cat': No such file or directory
mv: cannot stat 'all.txt.txt': No such file or directory

Where have I gone wrong?

  • I hope this isn't a school assignment. First, as the answerer pointed out, 'cat bastename.txt' is a literal string. What you intended was cat bastename.txt with backticks instead of single quotes (although the dollar sign and parentheses works as well) Also, entering echo $i in your loop to see what your code is actually doing is a good strategy as a first step in debugging. – anotherguy Jan 20 '19 at 19:20
3

'cat basenames.txt' with single quotes is a string literal, so your for loop is passing the whole thing to cd

Presumably you want to evaluate the command cat basenames.txt and pass the result, one at a time, to your loop body: that would require backticks

for i in `cat basenames.txt`

or the more modern and recommended syntax

for i in $(cat basenames.txt)

HOWEVER looping over the output of a cat command will be subject to word splitting and shell glob expansion - so really I'd recommend re-writing the loop as

while IFS= read -r i
do
        cd "$i"
        mv "${i}.html" "/c/Users/USER/directory1"
        cd ..

done < basenames.txt
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.