Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script use function call in string substitution

in a bash script I call an external script that gives me the status of a program, like

~/bin/status

which returns something like

program is running

or

program is halted

Now I want to use only the last word, which I get e.g. with

STATUS=$(~/bin/status)
echo ${STATUS##* }

which gives me 'running' or 'halted', so far so good.

What I wonder is, is there a way to do this without storing the output of the status-script in a variable? I mean something like

echo ${$(~/bin/status)##* }

or

echo ${(~/bin/status)##* }

This call returns an error message 'bad substitution'. I've already searched for a solution but didn't find any. Maybe here is some bash specialist who can answer this? And no, it is not really a problem to do this with a variable, I'm just curious :-).

like image 570
jokey Avatar asked Jun 16 '26 10:06

jokey


1 Answers

The presented way:

status=$(~/bin/status)
echo "${status##* }"

is the good and best way to do it. Use it, it is great.

Notes: I typically use $tmp variable name for such things. Prefer lower case variables for script temporary variables, use upper case for exported variables. Use quotes to prevent filename expansion. Check your script with shellcheck.

like image 122
KamilCuk Avatar answered Jun 17 '26 23:06

KamilCuk