the*_*ien 9 variables bash shell
我正在写一个创建用户帐户的bash脚本.根据特定条件从文件中提取用户名和密码哈希.密码哈希自然包含'$'分隔哈希的字段(例如$ 1 $ {SALT} $ ...).
问题是-p选项useradd需要在密码哈希周围使用单引号,以防止'$'字段作为变量进行插值.传递变量时,为了正确插值,引号需要加倍.单引号将变量视为字符串.
但是,如果我用双引号传递变量,则扩展变量,然后将每个'$'视为一个变量,意味着密码永远不会正确设置.更糟糕的是,有些变量在其中有大括号('{'或'}'),这进一步扼杀了事情.
如何传递这样的值并确保它完全插值而不需要shell修改?
所有内插变量完整的特定代码行示例:
# Determine the customer we are dealing with by extracting the acryonym from the FQDN
CUSTACRO=$(${GREP} "HOST" ${NETCONF} | ${AWK} -F "." '{print $2}')
# Convert Customer acronym to all caps
UCUSTACRO=$(${ECHO} ${CUSTACRO} | ${TR} [:lower:] [:upper:])
# Pull the custadmin account and password string from the cust_admins.txt file
PASSSTRING=$(${GREP} ${CUSTACRO} ${SRCDIR}/cust_admins.txt)
# Split the $PASSSTRING into the custadmin and corresponding password
CUSTADMIN=$(${ECHO} ${PASSSTRING} | ${CUT} -d'=' -f1)
PASS=$(${ECHO} ${PASSSTRING} | ${CUT} -d'=' -f2)
# Create the custadmin account
${USERADD} -u 20000 -c "${UCUSTACRO} Delivery Admin" -p "${PASS}" -G custadmins ${CUSTADMIN}
Run Code Online (Sandbox Code Playgroud)
编辑:扩展代码以获取更多上下文.
Eev*_*vee 20
当您使用单引号分配给$PASS.双引号不会递归扩展变量.
注意:
$ foo=hello
$ bar=world
$ single='$foo$bar'
$ double="$foo$bar"
$ echo "$single"
$foo$bar
$ echo "$double"
helloworld
Run Code Online (Sandbox Code Playgroud)
引号仅影响shell解析文字字符串的方式.shell在变量"内部"看起来的唯一一次就是当你根本不使用任何引号时,即使这样,它也只会进行分词和通配符扩展.