8

In Bash, it is possible to do string manipulation on a variable, for example to get the current runlevel on a Linux machine:

current_runlevel=$(runlevel) #sample output: 'N 2'
current_runlevel=${current_runlevel#* }
echo $current_runlevel #sample output: '2'

However, is it possible to combine the two lines, so no intermediate variable is required? Using the same example, I want it to look something like:

current_runlevel=${$(runlevel)#* }

This does not work, giving the error

${$(runlevel)#* }: bad substitution

Any ideas on how it might be possible to use a literal string in Bash string manipulation expressions?

2
  • 1
    @Bill Please don't use "pls." And I don't see how that question is relevant anyway. Commented Jun 28, 2013 at 13:10
  • 3
    FWIW, you can do it in zsh, echo ${$(echo foo)#f} -> oo Commented Oct 23, 2013 at 16:25

1 Answer 1

5

Well, not really. You can, though use sed, or something similar, like:

current_runlevel=$( runlevel | cut -d' ' -f2 )

Using intermediary variable will be a bit faster though.

Sign up to request clarification or add additional context in comments.

1 Comment

I would much prefer using an intermediate variable than creating a new process. It is neater, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.