【问题标题】:Custom arguments in bash scriptbash 脚本中的自定义参数
【发布时间】:2018-10-10 08:49:45
【问题描述】:

我必须编写一个脚本,该脚本将根据从命令行传递的参数执行各种任务。脚本的名称是“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 命令未找到]

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

【问题讨论】:

  • [ 之后和] 之前添加空格。还要加倍你的变量"$arg"。最后去shellcheck.net验证你的文件
  • 空格已修复,谢谢@oliv

标签: linux bash terminal arguments


【解决方案1】:

您可能希望考虑改用bash shell 内置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

在命令行上($ 是提示符):

$ ./gash.sh -r fred.txt
r
fred.txt

$ ./gash.sh -r
./gash.sh: option requires an argument -- r

$ ./gash.sh -x
./gash.sh: illegal option -- x

$ ./gash.sh -dr fred.txt
d
r
fred.txt

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-02
      • 2015-09-05
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      相关资源
      最近更新 更多