bash脚本中的自定义参数

时间:2018-10-10 08:49:45

标签: linux bash terminal arguments

我必须编写一个脚本,该脚本将根据从命令行传递的参数来执行各种任务。脚本的名称是“ safeDel.sh” 到目前为止,我的情况如下:

#!/bin/bash

arg=$1
r_file=$2

if [$arg == '-l']
then
#List all files in trash can
echo '$arg'

elif [$arg == '-r']
then
#recover r_file
echo '$arg'

elif [$arg == '-d']
then
#Delete (interactively?) the contents of trash directory 
echo '$arg'

elif [$arg == '-t']
then
#Display total usage in bytes of trash directory
echo '$arg'

fi

在这个阶段,我只是试图使用if / else语句来打印出适当的参数。但是,如果键入“ ./safeDel.sh -r”,则输出为:

./ safeDel.sh:第6行[-r命令未找到]

./ safeDel.sh:第11行[-r命令未找到]

./ safeDel.sh:第16行[找不到-r命令]

./ safeDel.sh:第21行[-r命令未找到]

什么是修改我的代码的正确方法,以便我可以使脚本根据传递的参数来执行某些任务?

2 个答案:

答案 0 :(得分:0)

您可能希望考虑使用内置col_names=FALSE的{​​{1}} shell。我假设只有bash选项才需要getopts,即r_file之后的-r

:

在命令行上(提示符为r):

#!/bin/bash

while getopts lr:dt arg
do
    case $arg in
        i) #List all files in trash can
           echo "$arg"      # Use double quotes, not single
           ;;
        r) #recover r_file
           r_file="$OPTARG"
           echo "$arg"   
           echo "$r_file"
           ;;
        d) #Delete (interactively?) the contents of trash directory
           echo "$arg"   
           ;;
        t) #Display total usage in bytes of trash directory
           echo "$arg"   
           ;;
    esac
done

答案 1 :(得分:-2)

在方括号[]中的文本周围添加空格可解决此问题。