如果用户错误地调用脚本,请使Bash脚本退出并打印错误消息
需要的脚本是
#!/bin/bash # Check if there are two arguments if [ $# -eq 2 ]; then # Check if the input file actually exists. if ! [[ -f "$1" ]]; then echo "The input file $1 does not exist." exit 1 fi else echo "Usage: $0 [inputfile] [outputfile]" exit 1 fi # Run the command on the input file grep -P "^[s]*[0-9A-Za-z-]+.?[s]*$" "$1" > "$2" 编辑,脚本已更改为 grep -P "^[s]*[0-9A-Za-z-]+.?[s]*$" $* if [ ! -f "$1" ]; then echo 'Usage: ' echo echo './Scriptname inputfile > outputfile' exit 0 fi 在没有参数的情况下调用脚本不会产生错误并且空白 Usage: ./Scriptname inputfile > outputfile 我有点代码 grep -P "^[s]*[0-9A-Za-z-]+.?[s]*$" $* 此代码拉出在其上有单个单词的行,并将输出泵送到新文件,例如
输出将是 This now 代码有效,用户使用./scriptname文件>调用代码.新文件 但是,我正在尝试扩展代码,以便在用户错误地调用脚本时向用户提供错误消息. 对于错误消息,我正在考虑回复像scriptname file_to_process>输出文件. 我确实试过了 if [incorrectly invoted unsure what to type] echo $usage exit 1 Usage="usage [inputfile] [>] [outputfile] 但是我运气不好.代码运行但如果我只使用脚本名称调用则不执行任何操作.此外,如果我仅使用scriptname和输入文件调用脚本,它将输出结果而不是退出并显示错误消息. 其他我尝试的是 if [ ! -n $1 ]; then echo 'Usage: ' echo echo './Scriptname inputfile > outputfile' exit 0 fi 鉴于到目前为止我收到的回复,我的代码现在是 #!/bin/bash grep -P "^[s]*[0-9A-Za-z-]+.?[s]*$" $* if [ ! -f "$1" ]; then echo 'Usage: ' echo echo './Scriptname inputfile > outputfile' exit 0 fi 在没有输入文件的情况下调用脚本时,脚本不执行任何操作,必须使用ctrl c中止,仍然尝试获取调用消息的回显. 解决方法
当你调用像./scriptname文件>这样的脚本时在newfile中,shell将文件解释为./scriptname的唯一参数.这是因为>是标准输出重定向运算符.
我想提出两种可能的替代方案: 备选方案1: ./scriptname 'file > newfile' 在这种情况下,检查格式的一种方法是 #!/bin/bash # Check if the format is correct if [[ $1 =~ (.+)' > '(.+) ]]; then # Check if the input file actually exists. if ! [[ -f "${BASH_REMATCH[1]}" ]]; then echo "The input file ${BASH_REMATCH[1]} does not exist!" exit 1 fi else echo "Usage: $0 "[inputfile] [>] [outputfile]"" exit 1 fi # Redirect standard output to the output file exec > "${BASH_REMATCH[2]}" # Run the command on the input file grep -P "^[s]*[0-9A-Za-z-]+.?[s]*$" "${BASH_REMATCH[1]}" 注意:如果要检查参数是否有效,通常最好在检查完成后运行命令. 备选方案2: ./scriptname file newfile 脚本看起来像这样 #!/bin/bash # Check if there are two arguments if [ $# -eq 2 ]; then # Check if the input file actually exists. if ! [[ -f "$1" ]]; then echo "The input file $1 does not exist." exit 1 fi else echo "Usage: $0 [inputfile] [outputfile]" exit 1 fi # Run the command on the input file grep -P "^[s]*[0-9A-Za-z-]+.?[s]*$" "$1" > "$2" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |