2

I am trying to write a bash script that creates new folders with the same name and structure as the directories on my server.

first I got all directories and sorted them by name:

   allDirLocal=$(cd $dirLocal ; find -type d |sort)

   allDirServer=$(ssh -t $remoteServer "cd $dirServer ; find -type d |sort")

then I compared them to find which directories are missing on my local drive:

newDirServer=$(comm -13 <(echo "$allDirLocal") <(echo "$allDirServer"))

and then I tried to create said Directories on my local machine:

for Dir in "$newDirServer" ; do mkdir $Dir ; done

However I end up with directories that look like this:

'exampleDir'$'\r' instead of just exampleDir

How do I fix this?

Edit: I don't want to create a directory tree from a txt file but from a variable, but I always end up with this weird format...

Edit: I literally just had to replace " " with ' ' to get rid of those escape signs in my directory names... It only took me a month to figure this out :P

Bunny
  • 23
  • 3
  • 1
    I'd guess your script itself contains CRLF line endings. check with `od -c script.sh` and fix with your editor or `dos2unix` – glenn jackman Feb 22 '19 at 21:14
  • Are you sure the file names on the remote server don't contain trailing CRs? I don't think the SSH session could add them, though perhaps investigate that, too. – tripleee Feb 23 '19 at 09:03
  • The sorting and local comparison are not really necessary, and complicate your processing. Just `mkdir -p` on each of the remote directory names; the ones which already exist will be no-ops. – tripleee Feb 23 '19 at 09:04

2 Answers2

0

replace this line

newDirServer=$(comm -13 <(echo "$allDirLocal" | tr -s '\r') <(echo "$allDirServer" | tr -s '\r'))

and execute the script with bash -x script.sh to follow the steps

Alpy
  • 759
  • 6
  • 9
0

This is your solution:

newDirServer=$(comm -13 <(echo "$allDirLocal") <(echo "$allDirServer") | sed 's@^\./@@g' | sed -r 's@\r@@g' | grep -v '^\.$')

I have removed initial ./ path and with sed I have removed all returns characters and . folder that is null.

Complete script:

#!/bin/bash
dirLocal="$HOME/etc.../etc...."
dirServer='/etc/etc/etc'
remoteServer='etcetcetc'
allDirLocal=$(cd "$dirLocal"; find -type d | sort)
allDirServer=$(ssh -t "$remoteServer" "cd \"$dirServer\"; find -type d | sort")
newDirServer=$(comm -13 <(echo "$allDirLocal") <(echo "$allDirServer") | sed 's@^\./@@g' | sed -r 's@\r@@g' | grep -v '^\.$')
while read line; do mkdir "$line"; done <<< "$newDirServer"
Darby_Crash
  • 446
  • 3
  • 6