没有变量的Bash字符串操作

Xen*_*hic 6 linux bash shell

在Bash中,可以对变量进行字符串操作,例如在Linux机器上获取当前运行级别:

current_runlevel=$(runlevel) #sample output: 'N 2'
current_runlevel=${current_runlevel#* }
echo $current_runlevel #sample output: '2'
Run Code Online (Sandbox Code Playgroud)

但是,是否可以组合两条线,因此不需要中间变量?使用相同的示例,我希望它看起来像:

current_runlevel=${$(runlevel)#* }
Run Code Online (Sandbox Code Playgroud)

这不起作用,给出错误

${$(runlevel)#* }: bad substitution
Run Code Online (Sandbox Code Playgroud)

关于如何在Bash字符串操作表达式中使用文字字符串的任何想法?

小智 5

好吧,不是真的.你可以,虽然使用sed,或类似的东西,如:

current_runlevel=$( runlevel | cut -d' ' -f2 )
Run Code Online (Sandbox Code Playgroud)

使用中间变量会更快一些.