我有以下bash:
#!/bin/bash
if ["$#" -ne "1"]; then
echo "Usage: `basename $0` <HOSTNAME>"
exit 1
fi
IPADDR=`ifconfig | head -2 | tail -1 | cut -d: -f2 | rev | cut -c8-23 | rev`
sed -i -e '1i$IPADDR $1\' /etc/hosts
Run Code Online (Sandbox Code Playgroud)
但是当我cat /etc/hosts:
$IPADDR
Run Code Online (Sandbox Code Playgroud)
我该如何处理此类问题?
您的问题是单引号内的变量'不会被 shell 扩展,而是保持不变。要引用您想要扩展的变量,请使用双引号",或者如果不需要它们,则省略引号,例如
sed -i -e '1i'$IPADDR' '$1'\' /etc/hosts
Run Code Online (Sandbox Code Playgroud)
在上面的行中$IPADDR, 和$1位于引号之外,并且将在参数被输入到 之前由 shell 扩展sed。