老兄,对于绝对的菜鸟问题很抱歉
以下代码有什么问题?
我喜欢有一个简单的脚本,上面写着MEH!当没有输入arg时,否则打印它。
#!/bin/bash
if [${#$1}==0] then
echo "MEH!";
else
echo $1;
fi
操作系统说第4行有错误(第4行意外的令牌) 对不起老兄 提前谢谢。
答案 0 :(得分:3)
您可能想要使用:
#!/bin/bash
if [ ${#1} -eq 0 ]; then
echo "MEH!";
else
echo $1
fi
当前if [${#$1}==0] then
条件中的问题:
[
和]
周围的空格。有关详细信息,请查看Charles Bailey在Why equal to operator does not work if its not surrounded by space?中的优秀答案。==
用于字符串比较。在这种情况下,您需要整数比较,即-eq
。请参阅手册中的Bash Conditional Expressions以获取完整列表。一般来说,如果你想检查你的脚本是否至少收到一个参数,你最好这样做:
if [ $# -ge 1 ]; then
echo "$# parameters given"
else
echo "no parameters given"
fi
或as commented by Charles Duffy:
if [ -z "$1" ] # true if the variable $1 has length 0
最后但并非最不重要:检查下面的评论,因为提供了良好的信息。