bash脚本中的多个参数

时间:2015-11-16 00:41:54

标签: bash gpio

我是bash的新手,我已经开始使用一个简单的bash脚本来打开或关闭raspberryPi上的GPIO引脚。我想像这样为脚本提供参数:script.sh GPIO_number start / on / off / clean。如何以最有效的方式继续此脚本?我坚持第二个论点。

#!/bin/bash

if [ -z $1 ]; then
        echo "Usage: gpioaction.sh GPIO start/on/off/clean"
        exit 1
fi

if [ -z $2 ]; then
        echo "Usage: gpioaction.sh GPIO start/on/off/clean"
        exit 1
fi

PIN=$1

start=$(echo "$PIN" > /sys/class/gpio/export;echo "out" > /sys/class/gpio/gpio$PIN/direction;echo "1" > /sys/class/gpio/gpio$PIN/value)
on=$(echo "1" > /sys/class/gpio/gpio$PIN/value)
off=&(echo "0" > /sys/class/gpio/gpio$PIN/value)
clean=&(echo "$PIN" > /sys/class/gpio/unexport)

1 个答案:

答案 0 :(得分:0)

你好像是在关闭' - 您为变量赋值(a =从某个命令输出)并快速运行所有命令;或许像这样的东西更接近你想要的东西:

function gpio_start {
echo "$PIN" > /sys/class/gpio/export
echo "out"  > /sys/class/gpio/gpio$PIN/direction
echo "1"    > /sys/class/gpio/gpio$PIN/value
}
###
case "$2" ### here you could use functions or simple commands lines
in
        start) replace_with_fucntion_or_start_steps ;;
           on) replace_with_fucntion_or_on_steps ;;
          off) replace_with_fucntion_or_off_steps ;;
        clean) replace_with_fucntion_or_clean_steps ;;
            *) echo "Usage: gpioaction.sh GPIO start/on/off/clean" ; exit ;;
esac
###  
Another, closer to what you have example:  

case "$2"
in
        start) gpio_start ;; ## use function for multiple commands
           on) echo "1" > /sys/class/gpio/gpio$PIN/value ;;
          off) echo "0" > /sys/class/gpio/gpio$PIN/value ;;
        clean) echo "$PIN" > /sys/class/gpio/unexport ;;
            *) echo "Usage: gpioaction.sh GPIO start/on/off/clean" ; exit ;;
esac

如果你使用案例陈述,那么你真的不需要你的第二次检查'使用' if'声明。

:)
戴尔