【问题标题】:How to pass default value to a variable in shell script?如何将默认值传递给shell脚本中的变量?
【发布时间】:2015-02-06 08:55:31
【问题描述】:

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

  1. 用户将给出文件名或目录名。
  2. 用户可以提供一个目标文件夹。如果用户不想要目标文件夹,他/她只需按 Enter。
  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

【问题讨论】:

  • 需要交互式输入的脚本不太有用,因为它们不能作为构建块合并到更大的脚本中,并且您放弃了 shell 的有用交互式功能,例如选项卡扩展等。明智的 cpd(对于默认复制)就像cpd () { cp "$1" "${2-/path/to/default}"; }一样简单
  • 谢谢,我只是学习。将尝试您的解决方案。 @tripleee

标签: linux shell if-statement ubuntu-14.04 logical-operators


【解决方案1】:

解决你的问题

改变

if [ "$destination_folder" = ""]

if [ "$destination_folder" = "" ]

并更改read -r directory_source

read -r source_folder

您也可以使用以下脚本。从命令行传递参数

#!/bin/sh
source_folder=$1

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

cp -a "$source_folder" "$destination"

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

运行

./script.sh source_folder [destination]

目的地是可选的

【讨论】:

  • 我已按照您给出的第一个指示进行操作。在 if 语句中的“]”之前添加了一个空格。但是,当没有为目的地提供任何内容时,它会引发以下错误。 "/usr/local/myfiles/copyDirToHTML.sh: line 8: =: command not found cp: cannot stat ‘’: No such file or directory”
  • 谢谢,知道了。虽然我的代码也有问题。并在下面添加。
  • 变量赋值中的= 周围不能有空格!此外,变量名前面的$ 符号是赋值错误。 destination=${destination_folder:-/var/www/html/} parameter expansion with defaults 在没有if ... else 的情况下也会这样做
  • @mata。感谢您的信息。我差点错过了。更新了我的答案。
  • 有一个特定的语法,所以你不需要明确的默认值。查看"${variable=value}""${variable-value}" 参数替换。
【解决方案2】:

我有办法解决这个问题。 工作代码是这样的:

$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

【讨论】:

  • 脚本开头的空变量插值不仅是多余的;如果可以在脚本启动时设置这些变量,它们可能会成为语法错误。