使用Shell脚本将文件从一个目录移动到另一个目录

时间:2018-07-23 11:31:04

标签: shell sh

我编写了一个shell脚本,该脚本将所有文件从特定目录移动到另一个目录。

#!/bin/bash

# Command to execute
execute_cmd=mv

path=/home/ypsvc/sa_automation

# Files inside actual_dir has to be moved
actual_dir="$path/sa_cx_data"

# This is the directory where files will be moved and kept
backup_dir="$path/file_backup/"

# Move each file from actual_dir to backup_dir

echo "Moving files to backup_dir"

for f in $actual_dir/*.xlsx
# echo f
do
 $execute_cmd "$f" $backup_dir
done

echo "Moving of files completed"

但是当我运行它时,它给出以下错误:

Moving files to backup_dir
: not found.sh: 14: file_backup.sh:
file_backup.sh: 16: file_backup.sh: Syntax error: word unexpected (expecting "do")

有人可以解决这个问题吗?

PS: file_backup 已创建,并且已对该脚本赋予适当的权限。

使用-x运行脚本会得到以下结果:

+
: not found.sh: 2: file_backup.sh:
+ execute_cmd=mv
+
: not found.sh: 5: file_backup.sh:
+ path=/home/ypsvc/sa_automation
+
: not found.sh: 7: file_backup.sh:
/sa_cx_datar=/home/ypsvc/sa_automation
+
: not found.sh: 10: file_backup.sh:
/file_backup//home/ypsvc/sa_automation
+
: not found.sh: 13: file_backup.sh:
+
: not found.sh: 15: file_backup.sh:
+ echo Moving files to backup_dir
Moving files to backup_dir
+
: not found.sh: 17: file_backup.sh:
file_backup.sh: 20: file_backup.sh: Syntax error: word unexpected (expecting "do")

2 个答案:

答案 0 :(得分:0)

尝试使用此代码

#!/bin/bash

# Command to execute
execute_cmd=mv

path="/home/ypsvc/sa_automation"

# Files inside actual_dir has to be moved
actual_dir="$path/sa_cx_data"

# This is the directory where files will be moved and kept
backup_dir="$path/file_backup/"

# Move each file from actual_dir to backup_dir

echo "Moving files to backup_dir"

for f in $(find $actual_dir -type f -name *.xlsx); ## used find here, with semicolon
do
 echo $f
 $execute_cmd $f $backup_dir
done

echo "Moving of files completed"

答案 1 :(得分:0)

您可以尝试一下,应该可以使用

#!/bin/bash
path="/home/ypsvc/sa_automation"
# Files inside actual_dir has to be moved
actual_dir="$path/sa_cx_data"
find $path -name '*.xlsx' -exec mv {} $actual_dir \;