[英]How to pass default value to a variable in shell script?
I have written this piece of code to move one directory to another. 我已经编写了这段代码将一个目录移动到另一个目录。 What I want with this code is as follows: 我想要的这段代码如下:
Here is the code. 这是代码。
$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"
Here is the input to this program: 这是该程序的输入:
Myfiles.sh (called the shell script in terminal)
Max Sum (This is the source directory)
(Pressed enter i.e. No destination given)
It gives following error: 它给出以下错误:
/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
To solve your problem 解决你的问题
Change 更改
if [ "$destination_folder" = ""]
to 至
if [ "$destination_folder" = "" ]
and change read -r directory_source
to 并将read -r directory_source
更改为
read -r source_folder
Also you can use the below script. 您也可以使用以下脚本。 Passing arguments from cmd line 从cmd行传递参数
#!/bin/sh
source_folder=$1
if [ $# -eq 2 ]; then
destination=$2
else
destination="/var/www/html/"
fi
cp -a "$source_folder" "$destination"
Where $#
is the number of arguments to the script. 其中$#
是脚本的参数数量。
$1 - > first argument...Similarly $2.. $ 1->第一个参数...类似地$ 2 ..
To run 跑步
./script.sh source_folder [destination]
destination is optional 目的地是可选的
I have got a solution to this problem. 我已经解决了这个问题。 The working code is like this: 工作代码如下:
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.