如何将默认值传递给 shell 脚本中的变量?

How to pass default value to a variable in shell script?

我写了这段代码来将一个目录移动到另一个目录。 我想要的代码如下:

  1. 用户将给出文件名或目录名。
  2. 用户可以提供目标文件夹。如果用户不想要目标文件夹 he/she 只需按回车键。
  3. 然后源目录将被复制到目标目录(如果指定)或默认目录(如果目标未指定)

这是代码。

$source_folder
$destination_folder
$destination
read -r directory_source
read -r destination_folder
if [ "$destination_folder" = ""]
then
    $destination = "/var/www/html/"
else
    $destination = "$destination_folder"
fi
cp -a "$source_folder" "$destination"

这里是这个程序的输入:

Myfiles.sh (called the shell script in terminal)
Max Sum (This is the source directory)
(Pressed enter i.e. No destination given)

它给出以下错误:

/usr/local/myfiles/copyDirToHTML.sh: line 6: [: : unary operator expected
/usr/local/myfiles/copyDirToHTML.sh: line 10: =: command not found
cp: cannot stat ‘’: No such file or directory

解决您的问题

改变

if [ "$destination_folder" = ""]

if [ "$destination_folder" = "" ]

并更改 read -r directory_source

read -r source_folder

您也可以使用下面的脚本。从 cmd 行传递参数

#!/bin/sh
source_folder=

if [ $# -eq 2 ]; then
    destination=
else
    destination="/var/www/html/"
fi

cp -a "$source_folder" "$destination"

其中 $# 是脚本的参数数量。
$1 -> 第一个参数...同样 $2..

到运行

./script.sh source_folder [destination]

目的地是可选的

我找到了解决这个问题的方法。 工作代码是这样的:

$source_folder
$destination_folder
read -r source_folder
read -r destination_folder
if [ "$destination_folder" = "" ]; then
   sudo cp -a "$source_folder" "/var/www/html/"
else
   sudo cp -a "$source_folder" "$destination_folder"
fi