0

My script is below, I can't remember how to make this make sense.

#!/bin/bash
input=$1
output=$2
cp $input $output_$(date +%m%d%y)

The goal is to run the script as follows

/path/script.sh /path/file_name /path/archive/

Archived file would then be /path/archive/file_name_090718

4
  • 4
    If you want the script to reference arguments passed to it, these would be in $1, $2, etc. In this case $1 would be /path/file_name and $2 would be /path/archive/
    – steve
    Sep 7, 2018 at 15:18
  • That is correct, the script will have varying arguments depending on what files it is archiving and where. $1 will always be the original file and $2 will always be the new destination.
    – Emile
    Sep 7, 2018 at 15:36
  • 3
    Don't be afraid to "play". Try commenting out the cp line and echo the values of ${input} and ${output}. Run the script with no/different arguments. What do you see? Add an echo to output ${output}_$(date +%m%d%y), what do you see? Once you've done that, you'll be in a better position to know what cp command to use. Sep 7, 2018 at 15:36
  • CURLY BRACKETS!! That's what I kept forgetting. If anybody else lands on this question, the answer is curly brackets.
    – Emile
    Sep 7, 2018 at 16:06

2 Answers 2

1

Wrapping ${output} in {} brackets allows the concatenation of the underscore and date. Alternatively you could just use cp $1 $2_$(date +%m%d%y).

script.sh

#!/bin/bash
input=$1
output=$2
cp ${input} ${output}_$(date +%m%d%y)

Usage:

$ ls
file_name script.sh
$./script.sh file_name archive
$ ls
archive_090718 file_name script.sh
2
  • You would also need to double quote the variable expansions to cope with filenames containing whitespace and/or characters that the shell would otherwise treat as globbing patterns. See e.g. unix.stackexchange.com/questions/131766/… The curly braces are only needed in the destination path where the value of the output variable is concatenated with an underscore.
    – Kusalananda
    Sep 7, 2018 at 16:26
  • The goal is to append the file_name while placing it in the archive. See my answer above.
    – Emile
    Sep 10, 2018 at 21:22
0

THE ANSWER IS CURLY BRACKETS!

This is how I did it; it's not the prettiest way to skin a cat...

#!/bin/bash
input=$1
output=$2
cp $input ${output}_$(date +%m%d%y)
$ ./script /usr/tmp/file_name /usr/tmp/arch/file_name
$ ls -l /usr/tmp/arch
-rw-rw-r-- 1 xxxxxx yyyyyyy 5 Sep  7 12:06 file_name_090718

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .