【问题标题】:Explain me 2 lines of this shell script解释一下这个 shell 脚本的 2 行
【发布时间】:2016-01-24 17:34:44
【问题描述】:

这是什么意思?

if [ -f $2/$1 ]

还有这一行:

cp $1 $2/$1

$2/$1 是否代表一个文件,因为它与 -f 相关联?

#!/bin/bash
if test $# -ne 2 
then
  echo "Numbers of argument invalid"
else
  if [ -f $2/$1 ]
  then
    echo "file already exist , replace ?"
    read return
    if test $return = 'y'
    then
      cp $1 $2/$1
    else
      exit
    fi

  else
    cp $1 $2/$1
  fi
fi

【问题讨论】:

  • 顺便说一句,这条线有问题。详情请转至shellcheck.net

标签: bash shell file-exists cp


【解决方案1】:

给定 2 个参数/名称($2$1),这是为了确保目录 $2 下名称为 $1 的文件存在。如果是这样,那么它将一个由$1 指示的本地文件复制到具有相同名称的目录$2 中。

但是,根据您的以下示例,它的使用方式略有不同。如果目标文件中不存在该文件,它会立即将文件复制到名称由$2 指定的子目录中。如果该文件确实存在于目标中,它首先会提示用户是否正常。覆盖现有文件。

http://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html

【讨论】:

  • 我认为 / 表示算术表达式,而它只是路径,谢谢
【解决方案2】:
./script.sh "tmp.txt" "/project"
echo $1 = tmp.txt
echo $2 = /project
$1 - file name
$2 - directory
if [ -f $2/$1 ] - checks if file exists, -f for files, -d for directory
cp $1 $2/$1 - copy file to directory/file_name
if [ -f /project/tmp.txt ]
cp tmp.txt /project/tmp.txt

【讨论】:

  • 非常感谢您的帮助。现在我明白我的问题出在哪里了,/ 只是代表路径。
猜你喜欢
  • 1970-01-01
  • 2017-09-02
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
相关资源
最近更新 更多