0

I found this shell script($1,$2 are directories):

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

it 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 will have a ".txt" extension. I can't figure out why cd "$1/$2" won't work doesn't basename strip the filename from a given directory? Could someone explain how this part: cd "$1/$(basename "$2")" works? Also $2 needs to be in separate quotes("$2") because of basename?

Charlie
  • 22,886
  • 11
  • 59
  • 90
newhere
  • 31
  • 5

2 Answers2

1

The basename removes the leading directory information. Assume that the sript is called with arguments like this:

$$> script usr/local/foo usr/local/bar

Now the $2 is equal to usr/local/bar.

If you only do cd $1/$2, the command will look like this:

cd usr/local/foo/usr/local/bar

But in reality, it should be

cd usr/local/foo/bar

It is removing this directory prefix from usr/local/bar is whhat is done by basename.

https://www.geeksforgeeks.org/basename-command-in-linux-with-examples/

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • and if I would call the script like this : script directory1 directory2(without the path just simply the directory name) than cd $1/$2 would work right? – newhere Apr 05 '21 at 18:35
0

Also $2 needs to be in separate quotes("$2") because of basename?

Yes, there's the outer set of expansions "$1/$(...)", and the inner expansion "$2" that both need to be quoted to prevent issues with word splitting which would otherwise break the command if $2 contained whitespace (or shell glob characters).

See e.g. Quoting within $(command substitution) in Bash on unix.SE for the details.

(Actually that should be cd -- "$1/$(basename -- "$2")" to guard against filenames/paths starting with -, too.)

ilkkachu
  • 6,221
  • 16
  • 30
  • @ikkachiu and why is % after f necessary I know that .* repeats 0 or an many times as possible but what does %? – newhere Apr 05 '21 at 19:01
  • @newhere http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion and http://mywiki.wooledge.org/BashFAQ/073?action=show&redirect=ParameterExpansion – ilkkachu Apr 05 '21 at 19:05