Search code examples
bashvariablesmv

Bash: passing a variable to mv command option


--Bash 4.1.17 (running with Cygwin)

Hello, I am trying to pass the date into the --suffix option on the move (mv) command. I am able to pass in a simple string (like my name) but unable to pass in the date. If you run the script below you will see that the mv command with the suffix="$var" works but suffix="$now" does not.

#!/bin/bash

dir="your directory goes here"

now="$(date "+%m/%d/%y")"

var="_CARL!!!"

echo "$now"

echo "$var"

cd "$dir"

touch test.txt

# error if already exists
mkdir ./stack_question

touch ./stack_question/test.txt

mv -b --suffix="$var" test.txt ./stack_question/

The idea is that if test.txt already exists when trying to move the file, the file will have a suffix appended to it. So if you run this script with:

--suffix="$var"

you will see that the stack_question directory contains two files:

test.txt & test.txt_CARL!!!

But, if you run this script with:

--suffix="$now"

you will see that in the stack_question directory only contains:

test.txt

Any help on this would be greatly appreciated!


Solution

  • It is because you have embedded / in your date format try

    now="$(date +%m_%d_%y)"