Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
插值包含'$';在bash脚本中_Bash_Shell_Variables - Fatal编程技术网

插值包含'$';在bash脚本中

插值包含'$';在bash脚本中,bash,shell,variables,Bash,Shell,Variables,我正在编写一个bash脚本来创建一个用户帐户。用户名和密码散列是根据特定条件从文件中提取的。密码散列自然包含分隔散列字段的“$”(例如$1${SALT}$…) 问题是,useradd的-p选项需要在密码哈希周围加上单引号,以防止“$”字段被插入为变量。传递变量时,为了正确地插值它,引号必须是双引号。单引号将变量视为字符串 但是,如果我以双引号传递变量,则该变量将展开,然后将每个“$”视为一个变量,这意味着密码从未正确设置。更糟糕的是,一些变量中有大括号(“{”或“}”),这会进一步把事情搞砸 我

我正在编写一个bash脚本来创建一个用户帐户。用户名和密码散列是根据特定条件从文件中提取的。密码散列自然包含分隔散列字段的“$”(例如$1${SALT}$…)

问题是,
useradd
的-p选项需要在密码哈希周围加上单引号,以防止“$”字段被插入为变量。传递变量时,为了正确地插值它,引号必须是双引号。单引号将变量视为字符串

但是,如果我以双引号传递变量,则该变量将展开,然后将每个“$”视为一个变量,这意味着密码从未正确设置。更糟糕的是,一些变量中有大括号(“{”或“}”),这会进一步把事情搞砸

我如何传递这样一个值,并确保它是完全插值的,而不被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}

编辑:扩展代码以获得更多上下文。

在分配给
$PASS
时使用单引号。双引号不会递归地扩展变量

注意:

$ foo=hello
$ bar=world
$ single='$foo$bar'
$ double="$foo$bar"
$ echo "$single"
$foo$bar
$ echo "$double"
helloworld

引号仅影响shell解析文本字符串的方式。shell看起来“在”变量内部的唯一时间是完全不使用引号,即使这样,它也只进行分词和通配符扩展。

是否尝试过使用反斜杠转义?例如,使用\'或\'可以通过将
set-x
放在所讨论的命令之前(以及之后的
set+x
来测试这样的脚本中发生了什么。这将使shell在执行命令之前打印每个命令。实际上,它打印一个等价的命令——一个具有相同的净结果,但可能具有不同的净结果的命令(但等效)引用/转义/等。这可以让你更好地了解实际发生了什么(一旦你习惯了等效位)。当使用命令扩展设置$PASS时,这可能吗?我已经用设置数据的所有代码更新了这个问题。实际上,看起来您不应该有问题;哈希值在任何时候都不是普通数据。(尽管您应该在所有变量和
$()
s周围使用双引号,以防它们包含空格。)小更正:在展开一个完全不在引号中的变量后,shell进行分词和全局(通配符)展开。@Gordondavison将永不停止。这就是我使用zsh;)的原因。)