在bash变量上使用cut时获取“未找到命令”

Getting “command not found” while using cut on bash variable

本问题已经有最佳答案,请猛点这里访问。

我在bash脚本中有两个变量

1
2
hostname="ab78ascsoadp003.abc.com"
Loc=`$hostname | cut -c3,4`

我收到错误ab78ascsoadp003.abc.com: command not found

我试图使用cut command,以便$Loc得到78


虽然您可以使用cut来实现这一点,但有时坚持使用bash是有用的:

1
2
hostname="ab78ascsoadp003.abc.com"
Loc=${hostname:3:2}

${parameter:offset:length} Substring Expansion. Expands to up to length characters of parameter starting at the character specified by offset. If length is omitted, expands to the substring of parameter starting at the character specified by offset. length and offset are arithmetic expressions

source: man bash


1
2
hostname="ab78ascsoadp003.abc.com"
Loc=$(cut -c3,4 <<<"$hostname")


你错过了echo

1
Loc=`echo $hostname | cut -c3,4`