Bash 脚本:参数无效

Bash 脚本:参数无效

为什么我不能echo $1 > /sys/class/backlight/acpi_video0/brightness在简单的 bash 脚本中使用?

它给了我错误:echo: write error: Invalid argument

答案1

尝试echo "$1" > /sys/class/backlight/acpi_video0/brightness

我敢打赌,shell 正在扩展 $1,因此 echo 认为它收到的是一堆参数,而不是一个字符串。

答案2

该文件是一个特殊文件。如果写入的内容不仅仅是数字,则无法写入。如果您尝试用 写入数字echo,则会在末尾得到一个换行符。echo -n解决了该问题。

编辑:此外,您可能遇到了我刚刚遇到的问题;您需要成为 root 用户,并且sudo无论出于什么原因都不会帮助您,这使得一直输入su; <your command>;非常繁琐exit。为此,我编写了一个(过于雄心勃勃的)python 脚本:

#!/usr/bin/python

from sys import *

PATH = "/sys/class/backlight/intel_backlight/brightness"

if len(argv) != 2:
    print("Usage: bright.py <brightness>")
    exit()

try:
    brightness = int(argv[1])
    if not 0 <= brightness <= 825:
        raise Exception()
except:
    print("<brightness> must be an integer between 0 and 825.")
    exit()

if brightness == 0:
    readString = raw_input("A value of 0 will turn off your screen. Are you sure you want to continue? [y/N] ")
    if readString != "y":
        exit()
elif brightness <= 5:
    with open(PATH, "r") as f:
        oldBrightness = int(f.read())
        if brightness < oldBrightness:
            readString = raw_input("A value of %i will make your screen very dark. Are you sure you want to continue? [y/N] " % brightness)
            if readString != "y":
                exit()

try:
    with open(PATH, "w") as f:
        f.write(str(brightness))
except:
    print("Failed to write to file. Are you root?")
    exit()

答案3

您应该检查的实际值是多少$1。此错误意味着您尝试写入无效值 - 要么超出范围,要么通常不是有意义的值。

乍一看,它似乎接受 0 到 8 范围内的整数(至少对我来说)。

答案4

尝试使用let

#!/bin/bash

POLKU='/sys/class/backlight/radeon_bl0/brightness'


if [ $# -eq "0" ]
    then
        echo 100 > $POLKU
    else
        let gg=$1
        echo $gg > $POLKU
fi

相关内容