【问题标题】:Difficulty with command line parameters命令行参数的困难
【发布时间】:2017-10-01 07:51:19
【问题描述】:

欢迎大家, 我需要提示用户输入“all、long、human 或 alh”。我已经开发了一些代码,但是有一个错误。我使用 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

代码本身可以工作,但是它不会根据所选参数显示任何目录列表。

输出:

请输入全部、long、human 或 alh:all
您已输入全部

【问题讨论】:

  • 我认为您需要运行ls -lls -a、....ls -alh,具体取决于给定的输入。您的脚本没有ls 命令。
  • 如果用户输入“foo”会怎样?
  • @choroba 只是说“你已经输入了 foo”
  • @LarsFischer 你能用下面的一段代码演示一下吗?

标签: linux bash unix scripting


【解决方案1】:

我会使用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

【讨论】:

  • 非常感谢@choroba,感谢您的努力!肯定会在短时间内尝试这些!
猜你喜欢
  • 2023-04-04
  • 2019-10-18
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
相关资源
最近更新 更多