在 bash 脚本中使用命令行参数作为 cp 和 mv 的目标

flo*_*lad 3 bash shell-script getopts

我试图通过运行带有标志/参数的脚本来复制文件(或重命名文件)以提供源文件名和目标文件名:

#!/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
Run Code Online (Sandbox Code Playgroud)

输出是一个错误:

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.
Run Code Online (Sandbox Code Playgroud)

是否cp(和mv)不接受参数化的目的地是哪里?我究竟做错了什么?

Adm*_*Bee 5

如果要接受参数:,则d在您的while getopts行中缺少必需的后面-d。因此你copy_dest是空的,因此cp抱怨“缺少操作数”。如果添加“调试”行,例如

echo "Source parameter: $copy_source"
echo "Destination parameter: $copy_dest"
Run Code Online (Sandbox Code Playgroud)

循环后,您将看到问题。要解决,只需添加:

while getopts s:d: flag
do
   ...
done
Run Code Online (Sandbox Code Playgroud)

另外,请注意,特别是在处理文件名时,您应该始终引用 shell 变量,如

cp "$copy_source" "$copy_dest"
Run Code Online (Sandbox Code Playgroud)

此外,请注意将脚本作为

sh test_cp.sh
Run Code Online (Sandbox Code Playgroud)

将覆盖 shebang-line #!/bin/bash,您不能确定它是在bash! 如果您想确保使用正确的 shell,您可以明确声明

bash test_cp.sh参数

或使脚本文件可执行并将其作为

./test_cp.sh参数