【发布时间】:2012-10-09 14:49:40
【问题描述】:
需要的脚本是
#!/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 is a multi word line this the above line is not now once again wrong
输出将是
This
now
代码有效,用户使用./scriptname file > newfile调用代码
但是,如果用户错误地调用脚本,我会尝试扩展代码以向用户提供错误消息。
对于错误消息,我正在考虑回显scriptname file_to_process > output_file 之类的内容。
我试过
if [incorrectly invoted unsure what to type]
echo $usage
exit 1
Usage="usage [inputfile] [>] [outputfile]
但是我运气不佳。如果我只使用脚本名称调用,代码会运行但什么也不做。此外,如果我只使用脚本名称和输入文件调用脚本,它将输出结果而不是退出并显示错误消息。
我尝试过的其他方法是
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 中止,仍然试图获得调用消息的回显。
【问题讨论】:
-
你使用的是
/bin/bash还是/bin/sh? -
在命令行使用
"$@"而不是$*;用空格保留文件名参数中的空格。如果您在表达式前面使用grep -P -e "...your regex..."和-e,则用户可以在命令行上键入-n或-l作为选项,grep将适当地修改其行为。 (在使用 GNUgetopt()来置换参数的系统上,您可能不需要指定-e;我不喜欢那个功能。) -
好吧,我现在将更改 $@
-
使用
[ -z "$1" ]代替[ ! -n $1 ]。还将 grep 放在参数计数测试之后,而不是之前。如果它在之前并且没有参数,它将坐在那里等待您在标准输入上输入输入。要进行实验,请在命令行中尝试grep x,不带文件名,然后在其中键入一些带和不带 x 的行,然后 ^D 退出。
标签: bash error-handling multiplicity