How can I write a user input value to a file in /sys/?

0
2
Asked By TechWizard42 On

I'm trying to create a script that sets up my battery charge threshold automatically. Previously, I used a command that involved 'sudo tee' and a heredoc to append a value to the charge stop threshold file. Now, I want to modify it to be more user-friendly by prompting for input with 'read -p "enter a percentage: " number'. However, when I replace the fixed value with '$number' or '${number}', it writes those exactly as text into the file rather than the value I input. I've also attempted to use 'sudo echo $number > /sys/class/power_supply/BAT0/charge_stop_threshold', but I keep getting a 'permission denied' error. How can I successfully take input from the user and write it into the specified file?

2 Answers

Answered By DevGeek07 On

When you quote the heredoc like '<< EOF', it treats everything literally, and no variable expansions happen. To allow for expansion of your variables, just remove the quotes. So instead of:

sudo tee -a /path/to/file << 'EOF'
$var
EOF

Do:

sudo tee -a /path/to/file << EOF
$var
EOF

You can also use a herestring for an even cleaner approach:

sudo tee -a /path/to/file <<< "$var"

Answered By CodeNinja99 On

The issue with your command is that 'sudo' only grants elevated permissions to the command it's used with, not to the output redirection. Instead of directly using 'sudo echo', try using 'sudo bash -c "echo your_value > your_file"'. This way, the entire command is run with sudo permissions. You might also want to use 'sudo tee' as a safer alternative. Here’s a little function to help:

function write_elevated_to() {
sudo tee "${1?}" > /dev/null
}

Then, you can call this function with your variable as the argument to write to the file.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.