0

I am using Linux and I want to write a shell script that takes two directories and moves the second directory in the first one (so the second directory becomes a subdirectory of the first one) and all the files from the second directory become ".txt" extension. For exemple: dir2 contains:

file1 file2 dir3 file3.jmp 

After running ./shell_scrip dir1 dir2, I want dir1 to contain dir2 and dir2 would look like this:

file1.txt file2.txt dir3 file3.txt 

I tried to change the extensions but I got this error:

mv: cannot stat `file1`: No such file or directory 

using the following code:

#!/bin/sh for file in $2/*; do f=$(basename "$file") mv "$f" "${f}.txt" done 
2
  • 1
    Put echo in front of the mv command to see where you're going wrong Commented Mar 31, 2021 at 18:29
  • 1
    "I want dir1 to contain dir2": what is dir1 here? Is the script supposed to create a new directory and move the existing dir2 into this new dir1? Commented Mar 31, 2021 at 18:39

1 Answer 1

1

You're not moving or referencing dir2. Try something like this:

#!/bin/sh mv "$2" "$1" || exit # Make $2 a subdirectory of $1 cd "$1/$(basename "$2")" || exit # Change directories for simplicity for f in *; do mv "$f" "${f%.*}.txt" # Add or change the extension done 

Adding || exit after the mv and cd commands will cause the script to exit if the command fails, which gives a little protection in case things aren't what you expect.

The expression ${f%.*} is the same as $f if there's no period in the name. Otherwise it removes the period (the last period) and everything after it.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.