2013-10-31 87 views
0

我想的inputLineNumber将值设置为20,如果没有值由用户给出由我试图检查[[-z“$ inputLineNumber”]],然后通过inputLineNumber = 20设定值。该代码给出了这条消息./t.sh:[-z:找不到作为控制台上的消息。如何解决这个问题?这是我的完整脚本。如何在Unix中输入错误/无效输入时设置默认值?

#!/bin/sh 
cat /dev/null>copy.txt 
echo "Please enter the sentence you want to search:" 
read "inputVar" 
echo "Please enter the name of the file in which you want to search:" 
read "inputFileName" 
echo "Please enter the number of lines you want to copy:" 
read "inputLineNumber" 
[[-z "$inputLineNumber"]] || inputLineNumber=20 
for N in `grep -n $inputVar $inputFileName | cut -d ":" -f1` 
do 
    LIMIT=`expr $N + $inputLineNumber` 
    sed -n $N,${LIMIT}p $inputFileName >> copy.txt 
    echo "-----------------------" >> copy.txt 
done 
cat copy.txt 

从@Kevin建议后改剧本。现在,该错误信息./t.sh:在第11行语法错误:`$”意外

#!/bin/sh 
truncate copy.txt 
echo "Please enter the sentence you want to search:" 
read inputVar 
echo "Please enter the name of the file in which you want to search:" 
read inputFileName 
echo Please enter the number of lines you want to copy: 
read inputLineNumber 
[ -z "$inputLineNumber" ] || inputLineNumber=20 

for N in $(grep -n $inputVar $inputFileName | cut -d ":" -f1) 
do 
    LIMIT=$((N+inputLineNumber)) 
    sed -n $N,${LIMIT}p $inputFileName >> copy.txt 
    echo "-----------------------" >> copy.txt 
done 
cat copy.txt 

回答

0

尝试从改变这一行:

[[-z "$inputLineNumber"]] || inputLineNumber=20 

要这样:

if [[ -z "$inputLineNumber" ]]; then 
    inputLineNumber=20 
fi 

希望这有助于。

+0

这不起作用。同样的错误:( – user2889968

0

从哪里开始?

您正在运行的/bin/sh但试图使用[[[[sh不能识别的bash命令。将shebang更改为/bin/bash(首选)或使用[代替。

您没有[[-z之间的空间。这会导致bash将其作为名为[[-z的命令读取,这显然不存在。你需要[[ -z $inputLineNumber ]](注意最后的空格)。在[[内引用并不重要,但如果您更改为[(请参见上面的内容),则需要保留引号。

你的代码说[[-z,但你的错误说[-z。选一个。

使用$(...)而不是`...`。反引号已被弃用,并且$()可以正确处理引用。

你不需要cat /dev/null >copy.txt,当然不是两次都没有写在它之间。使用truncate copy.txt或只是简单>copy.txt

您似乎有不一致的引用。引用或转义(\x)带有特殊字符(~, `, !, #, $, &, *, ^,(), [], \, <, >, ?, ', ", ;)的任何东西或空格以及任何可能有空格的变量。您不需要引用没有特殊字符的字符串文字(例如":")。

而不是LIMIT=`expr...`,使用limit=$((N+inputLineNumber))

+0

感谢您对整个脚本的宝贵意见,而不仅仅是手头上的问题。显然,正如您可能已经猜到的,我对Unix非常陌生(基本上是我的第一个脚本:))。我所做的更改 - > 1)更改了** [[**到** [** 2]现在引用已修复! 3)/ dev/null被truncate替换。 4)是的,我发布后,我也注意到了两倍的部分。尽快纠正它,但你更快!:D没有做过的变化 - > 1)尽管z之前的空间已经存在于我的代码中了。虽然不知道如何在粘贴时删除: – user2889968

+0

关于最后一个** LIMIT **部分,我也改变了你可能在这个问题上有一两个疑问?这个双括号在这里的瞳孔是什么?如何在没有$的情况下获取该变量的值(这是双括号的目的)? – user2889968

+0

'$((... )''比'expr'更干净,是的,你不需要sigil('$')。 – Kevin

相关问题