带'+'操作数的Bash错误//引用误用

时间:2016-07-31 11:41:57

标签: bash alias quotes

☿[~]$ hdd
bash: +: syntax error: operand expected (error token is "+")

这个别名突然停止了它的工作:

☿[~]$ echo Σ= $(($(df -BMB /dev/sdb1 --output=used | tail -1 | grep -o '[0-9]*')+$(df -BMB /dev/sdc1 --output=used | tail -1 | grep -o '[0-9]*'))) Mb
Σ= 3782845 Mb

但命令仍然有效:

    #START
from random import randrange

#Display Welcome
print("--------------------")
print("Number guessing game")
print("--------------------")

#Initilize variables
randNum = 0
userNum = 0

#Computer select a random number
randNum = randrange(10)

#Ask user to enter a number
print("The computer has chosen a number between 0 and 9, you have to guess the number!")
print("Please type in a number between 0 and 9, then press enter")
userNum = input('Number: ')

#Check if the user entered the correct number
if userNum == randNum:
    print("You have selected the correct number")
else:
    print("Incorrect")

1 个答案:

答案 0 :(得分:5)

不要使用别名;改为定义一些函数。

get_space_used () {
    df -BMB "$1" --output=used | tail -1 | grep -o '[0-9]*'
}
hdd () {
    sdb1=$(get_space_used /dev/sdb1)
    sdc1=$(get_space_used /dev/sdc1)
    echo "$(( sdb1 + sdc1 ))"
}

这使得引用更容易,重构代码重复,并且更容易确定出现错误时的问题。在您的情况下,第二个df管道出现问题,因为bash正在尝试执行类似echo $(( foo + ))的内容。