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

Move files between directories using shell script

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

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

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

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

我环顾四周 forums/documentation 似乎这些命令应该像在命令行中一样工作,但我似乎无法在脚本中执行相同的操作。

如果有人能解释我的意思 missing/not 理解那就太好了。

谢谢。

在第二行中,您将当前目录更改为 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(打印工作目录),这有帮助

您可以这样创建脚本:

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

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