2

I need to copy a file from one location to another while renaming the file with adding date and time stamp YYYYMMDDHHmmSS in this Format only using shell.

My Bash shell code:

cd $1
f1=Sup_Org_File_
for f in *.xml
do 
   cp -v "$f" $2/"${f1%}"$(date +%F%H:%M).xml
   cp -v "$f" $3/"${f1%}"$(date +%F%H:%M).xml
done
Paweł Obrok
  • 22,568
  • 8
  • 74
  • 70
  • 1
    Why do you copy twice? What should `$2` and `$3` contain? You'll want to quote them both, and `$1` too; see [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Jul 28 '20 at 15:18
  • What is the purpose of `%` in `${f1%}` ? – M. Nejat Aydin Jul 28 '20 at 15:38

2 Answers2

1

hope this helps you

for Bash shell Script

cd path_to_file
for f in *.xml
do 
   cp -v "$f" path_to_copy_file/"${f%.xml}"$(date +%Y%m%d%H%M%S).xml
done
1

Just "${f1%}" doesn't do anything useful; you want to put a pattern for something to actually remove after the %; and of course you probably want to remove a suffix from f, not from f1. (Giving your variables sensible names also helps.)

It's not clear what you expect $2 and $3 to contain, but they probably won't work correctly after you cd $1 (and all three of these should be quoted anyway).

Guessing a bit as to what you actually want, try this:

#!/bin/sh
d=$(date +'%F%H:%M)
for f in "$1"/*.xml
do
    # Trim directory prefix
    b=${f#$1/}
    # Trim .xml suffix
    b=${b%.xml}
    # Copy
    cp -v "$f" "$2/$b$d".xml
    cp -v "$f" "$3/$b$d".xml
done

There are no Bashisms here so I put a /bin/sh shebang on this.

tripleee
  • 175,061
  • 34
  • 275
  • 318