命令行参数难度

时间:2017-05-03 12:58:16

标签: linux bash unix scripting

欢迎所有人, 我被要求提示用户输入所有,长期,人或类似的东西。我已经开发了一些代码但是有一个错误。我使用shellcheck.net来检查我的代码的语法是否合适。

程序本身应该提供文件和目录列表(基于收到的命令行参数),如果未选择上述选项之一,也会显示错误消息。

  • “all” - 不要隐藏以。开头的条目。
  • “long” - 使用长列表格式
  • “human” - 使用长的列表格式和人类可读的打印尺寸 格式
  • “alh” - 完成以上所有

这是我的代码:

read -p "Please enter all, long, human or alh: " userInput

if [ -z "$userInput" ];
then
print f '%s/n' "Input is not all, long human or alh"
exit 1
else 
printf "You have entered %s " "$UserInput"
fi

代码本身有效,但它不会根据所选参数显示任何目录列表。

输出:

  

请输入all,long,human或alh:all
  您已输入所有

1 个答案:

答案 0 :(得分:0)

我使用case命令

#!/bin/bash

read -p "Please enter all, long, human or alh: " userInput

case "$userInput" in
    (all) flags=a;;
    (long) flags=l;;
    (human) flags=lh;;
    (alh) flags=alh;;
    (*) printf '%s\n' "Input is not all, long human or alh"
        exit 1;;
esac

ls -$flags

或者,您可以将标志存储在关联数组中:

#!/bin/bash

read -p "Please enter all, long, human or alh: " userInput

declare -A flags
flags=([all]=a
       [long]=l
       [human]=lh
       [alh]=alh
)

flag=${flags[$userInput]}
if [[ -z $flag ]] ; then
   printf '%s\n' "Input is not all, long human or alh"
   exit 1
fi

ls -$flag