使用shell脚本在目录之间移动文件



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

  • 在目录(child-directory-a(中创建一个文件
  • 移动到它所在的目录
  • 将文件移动到另一个目录(child-directory-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等(,但都没有用。我不明白为什么它不起作用。

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

如果有人能解释我遗漏/不理解的地方,那就太棒了。

谢谢。

您可以创建这样的脚本:

#!/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。它会告诉你所在的目录。

使用第二行,将当前目录更改为child-directory-a因此,在您的第三行中出现了一个错误,因为在子目录child-directory-a中没有子目录

你的第三行应该是:

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

脚本的第4点应该是:

cd ../child-directory-b

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

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

mv test.txt ..

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

#!/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}" ../

最新更新