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

问题描述:

我写了这段代码将一个目录移动到另一个。 我想要的代码如下:如何将默认值传递给shell脚本中的变量?

  1. 用户将给出一个文件名或目录名。
  2. 用户可以给一个目标文件夹。如果用户不需要目的地文件夹,他/她只需按下输入键。
  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 
+0

是什么问题? – Prashant 2015-02-06 08:58:22

+1

需要交互式输入的脚本不太有用,因为它们不能作为构建块并入较大的脚本中,并且会放弃shell等有用的交互功能,例如制表符扩展等。一个明智的'cpd'(用于默认复制)将是简单为'cpd(){cp“$ 1”“$ {2-/path/to/default}”; }' – tripleee 2015-02-07 07:37:34

+0

谢谢,我只是在学习。将尝试你的解决方案。 @tripleee – InsomniacSabbir 2015-02-07 13:17:31

解决您的问题

变化

if [ "$destination_folder" = ""] 

if [ "$destination_folder" = "" ] 

,改变read -r directory_source

read -r source_folder 

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

#!/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] 

目的地是可选

+0

我遵循你给出的第一条指示。在if语句中的“]”前加上一个空格。但是在给目的地什么都不给的情况下会引发以下错误。 “/usr/local/myfiles/copyDirToHTML.sh:第8行:=未找到命令 cp:can stat'':没有这样的文件或目录” – InsomniacSabbir 2015-02-06 09:09:34

+1

已完成更改。检查编辑 – 2015-02-06 09:33:22

+0

谢谢,明白了。尽管我的代码也遇到了问题。并添加到下面。 – InsomniacSabbir 2015-02-06 11:04:02

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

$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 
+0

脚本开始处的空变量插值不仅是多余的,如果在脚本启​​动时可以设置这些变量,它们可能会变成语法错误。 – tripleee 2015-02-07 07:30:25