首页 > 解决方案 > bash 脚本接受 cp 文件 >> .bak 或 .190318 选项的命令行参数(文件)和选项(扩展名)

问题描述

这是我所拥有的:

    #!/bin/bash
    #Create script that passes a command line argument of file
    # with options to create backup of the file
    # with either the .bak or .190318 extension

    #Create backup and timestamp ext
    backup=$".bak"
    timestamp=$".190318"
    #Create file var to hold passed arg
    file=$1

    #while loop to set arg -w options
    while [ -n "$1" ]
    do

        case "$1" in
            #Option for backup ext
            -a)  echo "Appending $file with $backup extension"
                 cp "$file"  "${file%.*}.bak" ;;
            #Option for timestamp ext
            -b)  echo "Timestamp appending $timestamp to file $1"
                 echo "$file" >> "$timestamp" ;;
            #Shift to end Options break to exit loop
            --)  shift
                 break ;;
         esac
     done     

然后我将 ./test14a -a file1 传递给命令行。

我的输出是:

cp: invalid option -- .
Try `cp --help' for more information.
Appending -a with .bak extension
cp: invalid option -- .

我尝试多次重写,传递文件并附加 $backup var 或 cp {$1} {newfile.bak},然后我添加了 $file 以在选项中使用,因为它 echo 不会反馈 $file 但-a(选项)。这就是为什么我在案例陈述中有不同的方法(用于测试的试错选项)。毕竟,我必须通过 echo 语句(可能是 if 语句)来查看它是否成功。如果你能给我指明一个方向,因为我认为过度思考弊大于利。先感谢您!

这是我的新代码:

#!/bin/bash
#Create script that passes a command line argument and options
#that creates a backup of a file with .bak or .190318 extensions
#Test for Success of the file created

#Create backup and timestamp ext
backup=$".bak"
timestamp=$".190318"
file=$2

#while loop to set arg -w options
while [ -n $1 ]
do

    case "$1" in
        #Option for backup ext
        -a)  echo "Appending $2 with $backup extension"
             cp  "$file"{,.bak}
             shift

             #Check for file success
             if [ -d==$file.bak ]
             then
                 echo "Success in making backup"
             else
                 echo "Your option failed"
             fi
             break ;;

        #Option for timestamp ext
        -b)  echo "Timestamp appending $timestamp to file $2"
             cp "$file"{,.$(date +"%y%m%d")}
             echo "$date" #Checking date output

             #Check for file success
             if  [ -d==$file.190318 ]
             then
                echo "Success in making timestamp file"
             else

                echo "Your option failed"
             #End if statement
             fi

             shift
             break ;;
         #Extra case to throw errors
         *)  echo "Unknown Option, Error"
             break ;;
    #End case statement
    esac
    shift
#End While loop
done

一切正常,但它很丑陋。有人对如何清理这个有建议吗?一种将 if 语句变成另一个选项的方法可能吗?并感谢您的调试想法,因为它显然帮助我了解了我失败的地方。

标签: bashcommand-line-argumentsoptions

解决方案


推荐阅读