【问题标题】:Move files between directories using shell script使用 shell 脚本在目录之间移动文件
【发布时间】:2021-05-25 15:30:29
【问题描述】:

一般来说,我是 linux 和 shell 脚本的新手。我在 WSL(Linux 的 Windows 子系统)上使用 Debian 发行版。我正在尝试编写一个非常简单的 bash 脚本,它将执行以下操作:

  • 在目录(子目录-a)中创建文件
  • 移动到它所在的目录
  • 将文件移动到另一个目录(子目录-b)
  • 移至该目录
  • 将文件移至父目录

这就是我目前所拥有的(现在尽量让事情变得非常简单)

touch child-directory-a/test.txt
cd child-directory-a
mv child-directory-a/test.txt home/username/child-directory-b

前两行有效,但最后一行出现“不存在这样的目录”错误。该目录存在并且是正确的路径(使用 pwd 检查)。我也尝试过使用不同的路径(即 child-directory-b、username/child-directory-b 等)但无济于事。我不明白为什么它不起作用。

我查看了论坛/文档,似乎这些命令应该像在命令行中一样工作,但我似乎无法在脚本中做同样的事情。

如果有人能解释我缺少/不理解的内容,那就太好了。

谢谢。

【问题讨论】:

  • 在第三行,您可能希望在home 前面加上//home/username/child-directory-b。你也可以使用特殊的环境变量$HOME:mv child-directory-a/test.txt "$HOME/child-directory-b/"

标签: linux bash shell debian


【解决方案1】:

您可以这样创建脚本:

#!/bin/bash

# Store both child directories on variables that can be loaded
# as environment variables.
CHILD_A=${CHILD_A:=/home/username/child-directory-a}
CHILD_B=${CHILD_B:=/home/username/child-directory-b}

# Create both child folders. If they already exist nothing will
# be done, and no error will be emitted.
mkdir -p $CHILD_A
mkdir -p $CHILD_B

# Create a file inside CHILD_A
touch $CHILD_A/test.txt

# Change directory into CHILD_A
cd $CHILD_A

# Move the file to CHILD_B
mv $CHILD_A/test.txt $CHILD_B/test.txt

# Move to CHILD_B
cd $CHILD_B

# Move the file to the parent folder
mv $CHILD_B/test.txt ../test.txt

考虑以下几点:

  1. 我们确保所有文件夹都存在并已创建。
  2. 使用变量避免拼写错误,并能够从环境变量加载动态值。
  3. 使用绝对路径来简化文件夹之间的移动。
  4. 使用相对路径将文件相对移动到我们所在的位置。

另一个可能有用的命令是pwd。它会告诉你你所在的目录。

【讨论】:

    【解决方案2】:

    使用第二行,将当前目录更改为 child-directory-a 所以,在你的第三行有一个错误,因为没有子目录 child-directory-a 进入子目录 child-directory-a

    你的第三行应该是:

    mv test.txt ../child-directory-b
    

    脚本的第 4 点应该是:

    cd ../child-directory-b
    

    (在该命令之前,当前目录为 home/username/child-directory-a,在此命令之后,它变为 home/username/child-directory-b)

    那么脚本的第 5 点和最后一点应该是:

    mv test.txt ..
    

    注意:您可以在脚本中使用命令 pwd(打印工作目录)在脚本的任何行显示当前目录,这很有帮助

    【讨论】:

      【解决方案3】:
      #!/bin/sh
      
      # Variables
      WORKING_DIR="/home/username/example scripts"
      FILE_NAME="test file.txt"
      DIR_A="${WORKING_DIR}/child-directory-a"
      DIR_B="${WORKING_DIR}/child-directory-b"
      
      # create a file in a directory (child-directory-a)
      touch "${DIR_A}/${FILE_NAME}"
      # move to the directory it is in
      cd "${DIR_A}"
      # move the file to another directory (child-directory-b)
      mv "${FILE_NAME}" "${DIR_B}/"
      # move to that directory
      cd "${DIR_B}"
      # move the file to the parent directory
      mv "${FILE_NAME}" ../
      

      【讨论】:

        猜你喜欢
        • 2013-11-16
        • 1970-01-01
        • 2011-06-19
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        • 2015-11-11
        • 2016-06-06
        • 1970-01-01
        相关资源
        最近更新 更多