使用 shell 脚本重命名 2 个文件

使用 shell 脚本重命名 2 个文件

我创建了一个名为的脚本rename_2_files.sh

#!/bin/sh
#_start
while getopts o: flag
do
   case "${flag}" in
       o) OPTION=${OPTARG};;
   esac
done
# declare variable
RENAME ="rename"
DEFAULT ="default"
# show all ExportP* files
ls '/home/dev/Documents/Work/info/Target_script/first'*
# rename file
if [["$OPTION" == "$RENAME"]]; 
then
   mv '/home/dev/Documents/Work/info/Target_script/first1.txt' '/home/dev/Documents/Work/info/Target_script/first1_ori.txt'
   mv '/home/dev/Documents/Work/info/Target_script/first2_SL.txt' '/home/dev/Documents/Work/info/Target_script/first2.txt'
fi
# show new name o files
ls '/home/dev/Documents/Work/info/Target_script/first'*

#_end

我使用运行它

sh rename_2_files.sh -o rename

回复:

rename_2_files.sh: 10: rename_2_files.sh: RENAME: not found
rename_2_files.sh: 11: rename_2_files.sh: DEFAULT: not found
/home/dev/Documents/Work/info/Target_script/first1.txt
/home/dev/Documents/Work/info/Target_script/first2_SL.txt 
rename_2_files.sh: 20: rename_2_files.sh: [[Rename: not found
/home/dev/Documents/Work/info/Target_script/first1.txt
/home/dev/Documents/Work/info/Target_script/first2_SL.txt

这方面存在哪些问题?请帮帮我...

答案1


我的脚本中有很多语法错误,但我使用 https://www.shellcheck.net/ 来纠正它们。

现在我的脚本('rename_2_files.sh')是:

#!/bin/sh
#_start
while getopts o: flag
do
    case "${flag}" in
        o) OPTION=${OPTARG};;
        *)
    esac
done
# declare variable
RENAME="rename"
DEFAULT="default"
# show all ExportP* files
ls '/home/dev/Documents/Work/info/Target_script/first'*
# rename file
if [ "$OPTION" = "$RENAME" ]; then
    mv '/home/dev/Documents/Work/info/Target_script/first1.txt' '/home/dev/Documents/Work/info/Target_script/first1_ori.txt'
    mv '/home/dev/Documents/Work/info/Target_script/first2_SL.txt' '/home/dev/Documents/Work/info/Target_script/first2.txt'
elif [ "$OPTION" = "$DEFAULT" ]; then
    mv '/home/dev/Documents/Work/info/Target_script/first1_ori.txt' '/home/dev/Documents/Work/info/Target_script/first1.txt'
    mv '/home/dev/Documents/Work/info/Target_script/first2.txt' '/home/dev/Documents/Work/info/Target_script/first2_SL.txt'
fi
# show new name o files
ls '/home/dev/Documents/Work/info/Target_script/first'*

#_end

并且,要调用我使用的脚本的执行: sh rename_2_files.sh -o renamesh rename_2_files.sh -o default

祝大家度过美好的一天并取得巨大的成功!

相关内容