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 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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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