shell脚本中的if else语句 [英] if else statement in shell script

查看:706
本文介绍了shell脚本中的if else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本根据您输入的参数执行不同的操作:

I have this script that does different things depending on the parameters you put as the input:

        #!/bin/bash
cadena="ls -alis"
while [ $# -e 0 ]
do
    case $1 in
        -p) [ $cadena = "$cadena | grep $2" ] ;;
        -o) [ if [ $2 = 'mida' ] then
                $cadena="$cadena -lS"
              elif [ $2 = 'inode' ] then
                $cadena="$cadena | sort -t 1" 
              fi
            ] ;;
        -d) [ if [ `expr substr $2 1 1`" = '/' ] then
                $cadena="$cadena $2"
              elif [ `expr substr $2 1 1`" != '/' ] then
                $cadena="$cadena `pwd`/$2" 
              fi
            ] ;;
        -s) [ $cadena="$cadena > $2" ] ;;
        shift 2
    esac
done
$cadena

使用 case 更新了代码。
错误与开头的错误相同,在第9行中使用 elif [$ 2 ='inode']然后语句,它表示错误的令牌。

Updated the code with case. The error is the same one a the beginning, in the line 9 with the elif [ $2 = 'inode' ] then statement, it says incorrect token.

推荐答案


  1. 不要混用单括号表示法 [] == ,它是 [... = ...] [[... == ...]]

您不需要两个 shift s,你可以转换2 代替(如果这真的是你想要的)。

You don't need two shifts, you can shift 2 instead (if this is really what you want).

您可以使用开关替换外部 if 以提高可读性,并避免嵌套 if 混乱:

You can replace the outer if with a switch for readability and avoid the nested if mess:

case $1 in
    -p) [...] ;;
    -o) [...] ;;
    -d) [...] ;;
    -s) [...] ;;
    *)  [...] ;;
esac


  • 您需要阅读 BashFAQ / 050又名我试图将一个命令放在变量中,但复杂的情况总是失败!

    这篇关于shell脚本中的if else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆