3

I am attempting to do copy a file (or rename a file) by running the script with flags/parameters to give both the source and the destination file name:

#!/bin/bash/

while getopts s:d flag
do
        case "${flag}" in
                s) copy_source=${OPTARG};;
                d) copy_dest=${OPTARG};;
        esac
done

echo "Copy a file input with argument to another file input with argument"
cp $copy_source $copy_dest

The output is an error:

sh test_cp.sh -s  file1.txt -d file2.txt
Copy a file input with argument to another file input with argument
cp: missing destination file operand after ‘file1.txt’
Try 'cp --help' for more information.

Does cp (and mv) not accept parametrized destination? What am I doing wrong?

5

You are missing the mandatory : after the d in your while getopts line if the -d is to accept a parameter. Therefore your copy_dest is empty, and hence cp complains about the "missing operand". If you add "debug" lines such as

echo "Source parameter: $copy_source"
echo "Destination parameter: $copy_dest"

after your loop, you will see the problem. To solve, simply add the ::

while getopts s:d: flag
do
   ...
done

Also, please note that in particular when dealing with filenames, you should always quote shell variables, as in

cp "$copy_source" "$copy_dest"

In addition, be aware that running a script as

sh test_cp.sh

will override the shebang-line #!/bin/bash and you cannot be sure that it is run under bash! If you want to ensure the correct shell is being used, you could either explicitly state

bash test_cp.sh arguments

or make the script file executable and run it as

./test_cp.sh arguments
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.