bannji
bannji

Reputation: 107

Would a "shell function" or "alias" be appropriate for this use

I'm currently trying to create an alias or shell function which I can run to check my battery life, in attempts to familiarize myself with aliases and bash. I have run into a problem where, I'm not receiving any feedback from my command and can not verify if it's working or if there are any steps i have left out that will give me my desired result.

Current .bashrc alias:

alias battery='upower -i $(upower -e | grep -e 'BAT'| grep -E "state|to\ full|percentage")'

Desired use:

b@localhost:~$ battery

Desired result:

state: discharging Time to empty: x.x Hours percentage: xx%

I have read the bash references for something that might help me here. I wasn't able to find anything that I think applies here. Thanks for your consideration!

Upvotes: 0

Views: 76

Answers (1)

Walter A
Walter A

Reputation: 20022

As @bannji already announced in a comment, he has fixed his command.
Old incorrect alias

'upower -i $(upower -e | grep -e 'BAT'| grep -E "state|to\ full|percentage")'

New correct alias

'upower -i $(upower -e | grep -e "BAT") | grep -E "state|to\ full|percentage"'

Most comments were talking about the interpretation of the quotes. That was not the problem here. The main difference is where the subcommand is closed. In the first case the subcommand is closed after the last grep, su upower -i gets nothing.
In the second command the second grep will filter the output of upower -i.

The difference in quotes is interesting in an other example.

addone() {
    ((sum=$1+1))
    echo "${sum}" 
}
i=1
alias battery='addone $(addone $i)'
i=4
battery
# other alias
i=1
alias battery2='addone $(addone '$i')'
i=4
battery2

Both battery commands will try to add 2 to the value of $i, but will give different results.
The command battery will add 2 to the current value 4 of $i, resulting in 6.
The command battery2 will add 2 to the value of $i at the moment that the alias was defined, resulting in 3.
Why?
In battery2 the string $i is surrounded by single quotes, but those single quotes are inside other ones. The result is that $i is evaluated and the alias is defined as

alias battery2='addone $(addone 2)'

Upvotes: 2

Related Questions