我是 Bash 编程新手,喜欢玩一玩。我正在尝试执行此脚本
#!/bin/bash
echo "Hello there, i am a little script so you can change a number of txt file
names at once"
read -p "I would like to know your name before we start, what is your name? " NAME
echo "Well hello there $NAME, nice to meet you im Scripty"
echo "Let's start"
read -p "What type of file would you like to rename(txt,sh,etc...)" ANSWER
case "ANSWER" in
[tT] | [tT][xX][tT])
echo "You selected a TXT file type,Good job $NAME"
;;
[sS] | [sS][hH])
echo "You selected a SH file type,Good job $NAME"
FILES=$(ls *.$ANSWER)
read -p "To what name you would like to change the file name?" NEW
for FILE in $FILES
do
echo "Renaming $FILE to new-$FILE"
mv $FILE $NEW-$FILE
done
这是我得到的输出
root@ubuntu:/home/daniel# ./change_the_name_of_the_file.sh
Hello there, i am a little script so you can change a number of txt file names at once
I would like to know your name before we start, what is your name? Daniel
Well hello there Daniel, nice to meet you im Scripty
Let's start
What type of file would you like to rename(txt,sh,etc...)txt
./change_the_name_of_the_file.sh: line 33: syntax error: unexpected end of file
而我不知道该如何拯救我自己的生命。
真的很需要这方面的帮助。
先感谢您
答案1
我修复了脚本中的一些问题,并添加了内联注释。如下所示:
#!/usr/bin/env bash
echo "Hello there, i am a little script so you can change a number of txt file names at once"
read -p "I would like to know your name before we start, what is your name? " NAME
echo "Well hello there $NAME, nice to meet you im Scripty"
echo "Let's start"
read -p "What type of file would you like to rename(txt,sh,etc...)" ANSWER
# ANSWER is a variable whose value must be accesses as $ANSWER.
# To avoid weird errors for ANSWERs with spaces in it, we put it in "double quotes":
case "$ANSWER" in
[tT] | [tT][xX][tT])
echo "You selected a TXT file type,Good job $NAME"
;;
[sS] | [sS][hH])
echo "You selected a SH file type,Good job $NAME"
;;
# If none of the above applies it's always good to have a default case:
*)
echo "You picked something else. Not sure whether I can handle that..."
;;
# close/end the opening "case" statement:
esac
# The original
# FILES=$(ls *.$ANSWER)
# parses the output of the `ls` command. This is ok for one-shot
# commands if you know for sure that your filenames do not contain strange
# characters. But the proper way is to use _globbing_ and assign
# the filenames to a bash array:
FILES=(*.$ANSWER)
read -p "To what name you would like to change the file name?" NEW
# Iterating an array needs some special syntax:
for FILE in "${FILES[@]}"
do
echo "Renaming $FILE to $NEW-$FILE"
# Again "double quotes" because the filenames may contain spaces.
# I prepended the line with "echo ..." so it does not do any harm.
echo mv "$FILE" "$NEW-$FILE"
done